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.
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:
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).
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:
I am Thinking of Building a Distributed Key value storage as a side Project What do you think are the core concepts i need to master for building this what would be the best place to start this with?
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: . 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.
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 , 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...
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 but it is still obtained by
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.
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:
-
A request comes in like this: localhost:8080/static/css/main.css
-
http.StripPrefix()
removes/static/
from the path, so it becomescss/main.css
-
But I don't understand why there isn't an error in
http.FileServer(http.Dir("./static"))
, sincecss/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
forhttp.FileServer
, sincecss/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/"))))
As the title imply, I am looking at how one would design a bubbletea app with several pages/views, each having a model, and wether there is a standard/widely accepted way to do it. I know how I would implement it in an ad-hoc fashion, but I wonder if there is some generic solution.
Hey guys, I am a NodeJs developer who is transitioning to Go. This community has helped me immensely in the journey.
I did this recently and would really appreciate any input especially on the things I need to improve upon, whether I am ready to take on Go Jobs.
PS: I am also on the lookout for Go jobs.
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.
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:
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
(), 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: . 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) }
Hey everyone,
I just wanted to share a project I've been working on called . 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 for more details. Any feedback or tips would be awesome.
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?
Hello! I'm back again with my tool , 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.g
oor 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.