Skip to main content

Get the Reddit app

Scan this QR code to download the app now
Or check it out in the app stores
r/golang icon
r/golang icon

r/golang

members
online


Who's Hiring? - June 2024

This post will be stickied at the top of until the last week of June (more or less).

Please adhere to the following rules when posting:

Rules for individuals:

  • Don't create top-level comments; those are for employers.

  • Feel free to reply to top-level comments with on-topic questions.

  • Meta-discussion should be reserved for the distinguished mod comment.

Rules for employers:

  • To make a top-level comment you must be hiring directly, or a focused third party recruiter with specific jobs with named companies in hand. No recruiter fishing for contacts please.

  • The job must involve working with Go on a regular basis, even if not 100% of the time.

  • One top-level comment per employer. If you have multiple job openings, please consolidate their descriptions or mention them in replies to your own top-level comment.

  • Please base your comment on the following template:

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





JSON response transform techniques JSON response transform techniques
help

I'm new to Go and still learning but this is something I've not found an answer for. Let's say I have a model with various properties such as name, email, ID, password etc and I want to return this object as a JSON response. I know in this instance I would set the json attributes on the model struct and use json.Marshal to produce the output.

But, what if certain responses only require certain properties to be returned so one endpoint might need to return a list of these models but only email and ID and another would be only name and email. This is obviously a basic example but in Laravel I would use a Resource and output only the required attributes for the endpoint.

Is there a "Go" way to do this or just a case of creating a second struct with only the desired properties or even creating a map with the required properties? I've done the latter but it feels like I'm missing a better way.


Is it worth porting my Java project over to Go? Is it worth porting my Java project over to Go?
help

I built a task manager/scheduling platform that runs off a custom scripting language that I created myself (plus custom serialization and log support). I've been seeing some really cool Golang CLI libraries and am tempted to try and port over my project (only ~10,000 lines, so nothing too crazy). Does this seem reasonable or no?

Here's my github for context: https://github.com/AndrewRoe34/agile-planner

Our current UI looks like it's from the 90s, and I'm definitely interested in learning more about Go (seems like a cool language if I'm being honest).


Batcher: Type-safe, automatic, asynchronous batch processing Batcher: Type-safe, automatic, asynchronous batch processing
show & tell

Sharing a small. simple library that I thought could be useful to others. This was born out of some personal needs (optionally grouping and batch processing incoming PubSub messages being one example). Batcher provides a type-safe, easy way to batch together arbitrary groups of items to be automatically and asynchronously processed. The README contains more information and clear examples.

If you find it useful or have any feedback, please let me know.

Repo: https://github.com/mikestefanello/batcher




Hey everyone! Can you please review my Go program? Hey everyone! Can you please review my Go program?
newbie

I started writing Go in 2019, but my projects were very basic and focused on automating simple tasks.

Here's the link to my repo: pingmullvad. It's a CLI tool that pings the Mullvad VPN servers and returns the complete list of servers with ping results and the top 5 fastest servers.

I'm open to criticism because I need to get better at writing Go programs. I would appreciate any comments or help you could provide.


gopls, how to disable auto import of unwanted library gopls, how to disable auto import of unwanted library

I am using gopls with Emacs. But whenever I type in some common word like "user", gopls automatically import a random library which is not required in my project at the top, because there is a module named "user". This feature is annoying. How can I turn it off? I still want the auto import but limited to the libraries in my current Go project.

I have read the settings https://github.com/golang/tools/blob/master/gopls/doc/settings.md, and cannot find anything related.

Solved: It has nothing to do with the configuration of gopls. It is because an Emacs package called Corfu is sending unnecessary select candidate signal to gopls when the current typing matches an exact candidate in the completion list from gopls. In short, if you are using Emacs with Corfu and facing the same issue, add this line into your config. (setq corfu-on-exact-match 'quit)

Thanks everyone for your help. I have learnt something from this. It absolutely has nothing to do with Go anyway...


How to use golang to connect to jmx of java service and retrieve exposed MBeans How to use golang to connect to jmx of java service and retrieve exposed MBeans
help

My project needs to obtain some indicators from the jmx of the service. The service implemented through java consumes more resources.

It is hoped that the memory consumption can be reduced by rewriting in golang But I don't know how to connect jmx -Dcom.sun.management.jmxremote.port through golang and get it from MBean.

I didn't find a suitable 3rd party library. Is there such a three-party library or other ways to achieve it? Looking forward to your reply.

PS: I found a third-party library gojmx but it is still obtained by calling Java




GoLang code coverage GoLang code coverage

One of our micro service is written in goLang. I want to calculate code coverage of it.

One way i found through via unit test cases. But i want code coverage like we have for java based services. One of our micro service is written in goLang. I want to calculate code coverage of it.

One way i found through via unit test cases. But i want code coverage like we have for java based services (Jacoco). In integration environment.

We have regression test suite of that service.

So, if we have some plugin or some library that can be used to calculate.

Please suggest how can I archive it.

Thanks.



How does a file server work in Go? How does a file server work in Go?
help

Hello, I am learning to program in Go and I have a question that I cannot understand.

I have a static file server like the following:

mux.Handle("GET /static/", 
  http.StripPrefix("/static/", 
    http.FileServer(http.Dir("./static"))))

So for example, this is how I understand everything happens:

  1. A request comes in like this: localhost:8080/static/css/main.css

  2. http.StripPrefix() removes /static/ from the path, so it becomes css/main.css

  3. But I don't understand why there isn't an error in http.FileServer(http.Dir("./static")), since css/main.css doesn't have an initial slash like /css/main.css would. This is because the initial slash was removed with /static/. So why does it work? As I understand it, the path would become ./staticcss/main.css for http.FileServer, since css/main.css lacks an initial slash and ./static lacks a final slash. Hahaha, it's confusing.

And why does this also work?

mux.Handle("GET /static/", 
  http.StripPrefix("/static", 
    http.FileServer(http.Dir("./static/"))))



Question about managing external sessions Question about managing external sessions

Hello. I'm fairly new to golang and I'm building an application for my team that consumes webhooks and then makes calls to various other tools to grab related data and action on them.

I can't recall where I "learned" this idea but currently I'm using a struct that I initialize when I create my cmd and then attach the various clients to the API client struct. The handlers, then utilize this struct on the method to access the various resources. The problem I'm having right now is that one of these clients has a session duration of 2 hours, and then it needs to be refreshed. However, I feel like the way that I'm initializing and using the client is a problem. So I'm looking for guidance on how I can improve this workflow or if I'm just doing something very anti-go.

In my `cmd` file:

logger := cmdutil.NewLogger("api")
defer logger.Sync()

awsC := aws.NewClient(logger)
cacheC := cmdutil.NewCache(awsC.AMS.RedisPassword, logger)
odinC := odin.NewClient(cacheC, awsC, logger).Login()

a := api.NewAPI(ctx, logger, cacheC, awsC, odinC)

NewAPI returns the following struct:

type api struct {
    aws        *aws.Client
    httpClient *http.Client
    logger     *zap.Logger
    cache      *cache.Cache
    odin       *odin.Client
}

Down stream in the handlers, I utilize a method to access this API struct as such:

func (a *api) WebhookHandler(w http.ResponseWriter, r *http.Request) {
    // truncated
    a.odin.GetAccountById(accountID);
    // truncated
}

At this point, I think I've made a design choice that is not great. In the `GetAccountById` function, I check session expiration and if needed make a call to refresh session however I'm unsure how I'm expected to update the initial client instance.

I'm not sure if for this use case, the concept of Globals is more appropriate or if there is another design pattern that makes more sense.

I'm looking for some guidance. If I haven't provided enough information, please let me know and I'm more than happy to share what I can.

Edit: Thinking about this more, this could still work if I split up my refresh logic from trying to return an entire client to just returning the necessary items and updating them but I still feel there is likely a better way.


Message dispatcher implementation in go Message dispatcher implementation in go
help

Hello everyone, I am building a message dispatcher in Go, but I am having problems with channels. Basically, I would like to dispatch many messages without blocking the function that calls dispatch, because the underlying buffered channel in message dispatcher will block if it's full. I don't want to use a new goroutine each time I dispatch a message. Is there any way I can achieve this? Maybe a queue with a condvar or an unbuffered channel?

Message dispatcher implementation: https://github.com/karyontech/karyon-go/blob/master/jsonrpc/client/message_dispatcher.go

UPDATE1: Basically, the code is part of a library where the user can subscribe to several jsonrpc methods from a server to receive notifications. For each subscription to a method, the message dispatcher registers a new channel. Once the client receives a new notification, the message dispatcher dispatches the notification to the corresponding subscription through the registered channel. The user should handle the number of messages entirely, the library should only pipe the messages. I have implemented the same functionality in Rust, where I am using concurrent_queue (https://docs.rs/concurrent-queue/latest/concurrent_queue/), which holds the messages in a queue until the user starts to receive and process them.

UPDATE2: I found a similar implementation in the Ethereum codebase: https://github.com/ethereum/go-ethereum/blob/55b483d82aa23772f8a8b330e3837a07c4fd00df/rpc/subscription.go#L324-L370. However, their solution is to unsubscribe from the server if they exceed a fixed number of messages. This approach involves implicit requests to the server, which the user is not aware of.

err := client.subscriptions.dispatch(ntRes.Subscription, *ntRes.Result)
if err != nil {
  return fmt.Errorf("Dispatch a notification: %w", err)
}

Genie - Project Review Genie - Project Review

Hey everyone,

I just wanted to share a project I've been working on called Genie. It's a CLI assistant that can run commands, generate images, create music, and fetch tech info right from your terminal.

I've only recently started learning Go, and I built Genie as part of my submission for the MLH Fellowship 2024. Would love to hear what you all think about it!

Check out the GitHub repo for more details. Any feedback or tips would be awesome.


How to correctly use context cancel() function? How to correctly use context cancel() function?
help

I have this function to start and return a PostgreSQL transaction which is being called for every API request (100/second).

func GetTxnClient(ctx context.Context, options *sql.TxOptions) (*DbTxClient, error) {
    txn, err := database.db.BeginTx(ctx, options)
    if err != nil {
       return nil, err
    }
    return &DbTxClient{Tx: txn}, nil
}

I want to add timeout in this, therefore I did this.

func GetTxnClient(ctx context.Context, options *sql.TxOptions) (*DbTxClient, error) {
    ctx, cancel := context.WithTimeout(ctx, 5 * time.Second)    
    defer cancel()
    txn, err := database.db.BeginTx(ctx, options)
    if err != nil {
       return nil, err
    }
    return &DbTxClient{Tx: txn}, nil
}

But due to the cancel() function being called before the function exits, I am unable to use the transaction as I get the error `sql: transaction has already been committed or rolled back`

Therefore, wanted to know how exactly to use the cancel() function?


Clai - Multi vendor LLM cli with dev and devops centric tooling Clai - Multi vendor LLM cli with dev and devops centric tooling
show & tell

Hello! I'm back again with my tool clai, v1.4.0!

Since 1.3.0 I've added:
* clai cmd mode - cli command suggestions, like many other llm cli tools
* clai setup command - configures the many configuration files via `clai`, instead of relying on manually editing them
* Multi-os releases + release script
* Stability upgrades

For those who aren't acquainted (which would be most if it not all, tbh 🤔), clai is a tool I wrote to help my day to day work as a cloud engineer. So I use it to interpret large documents (cat document | clai -i q analyze this document: {}), auto-write code clai -g 'internal/handler.go' -r q write unittests for this file > internal/handler_test.goor give suggestions for design cat stacktrace | clai -t -t q find where this stacktrace originates from and a solution: {}<- this example uses tools which clai calls to analyze the local filesystem.