Skip to content

Instantly share code, notes, and snippets.

@mvndaai
Last active October 28, 2024 19:42
Show Gist options
  • Save mvndaai/0ed68202ff731d7abaa58ea790d9e333 to your computer and use it in GitHub Desktop.
Save mvndaai/0ed68202ff731d7abaa58ea790d9e333 to your computer and use it in GitHub Desktop.
Add ctx to all functions

Backaground

The package ctx was adding to Golang after people had started using requests. In order to use ctxerr you need context passed with every function that returns and error. This is a find and replace that adds ctx context.Context to all functions that return an error.

What to do

  1. Open VSCode or Curser and do an editor serach cmd + shift + f
  2. Set it to regex find by clicking the .* button
  3. Paste find below as the search
  4. In files to include add *.go
  5. In files to exclude add mock_*.go, *_test.go
  6. Click the > to allow replace
  7. In the replace field paste below
    • The $1 and $4 are the matched groups in ()
  8. Make sure you didn't change interface functions like MarshalJSON or handler funcs
  • Empty parameter
    • Find - (func (\(.*\) )*[A-za-z]+)(\()(?!ctx)(\).*error.*\{)
    • Replace - $1(ctx context.Context$4
  • Has parameters (needs a comma)
    • Find - (func (\(.*\) )*[A-za-z]+)(\()(?!ctx)(.*[a-z]+\).*error.*\{)
    • Replace - $1(ctx context.Context, $4

Testing

In regex101 I was matching against this list

func Foo() {
func Foo() error {
func (h *hello) Foo() {
func (h *hello) Foo() error {
func (h *hello) Foo(s string) error {
func (h *hello) Foo() (int, error) {
func Foo() string {
func Foo() (string, int) {
func Foo(s string) (string, error) {

func Foo(ctx context.Context) {
func Foo(ctx context.Context) error {
func (h *hello) Foo(ctx context.Context) {
func (h *hello) Foo(ctx context.Context) error {
func (h *hello) Foo(ctx context.Context, s string) error {
func (h *hello) Foo(ctx context.Context) (int, error) {
func Foo(ctx context.Context) string {
func Foo(ctx context.Context) (string, int) {
func Foo(ctx context.Context, s string) (string, error) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment