0

I'd like to do something like the following in Go, where c/c.go contains:

package c

import (
    a "github.com/.../a"
    b "github.com/.../b"
)

func CallHandler(pkgName string) (err error) {
    pkg, err := DereferencePackage(pkgName)
    ...

    method, err := GetMethod(pkg, "Handler")

    if err != nil {
        return err
    }

    return method()
}

...

{
    err = CallHandler("a")
    ...
    err = CallHandler("b")
    ...
}

a/a.go contains:

package a

func Handler() (err error) {
    // Do whatever
    return err
}

and b/b.go contains:

package b

func Handler() (err error) {
    // Do whatever
    return err
}

An obvious solution would be a switch:

func CallHandler(pkgName string) (err error) {
    switch pkgName {
    case "a":
        return a.Handler()
    case "b":
        return b.Handler()
    default:
        return fmt.Errorf("no handler defined for %s", pkgName)
    }
}

but I wondered if it's possible to do this a bit more elegantly, perhaps using the reflect package. Another way to ask the same question is, can a package be an interface in Go?

Scott Deerwester
  • 3,503
  • 4
  • 33
  • 56
  • 1
    You can see the package name in the `reflect.Type`, but I would suggest that it's better to constrain package-specific behavior to the individual packages. If you want to simply register handlers by name, lots of packages use that pattern and relying on the package name just seems like added work and a little too "magic" – JimB Jan 13 '21 at 14:35
  • 2
    "can a package be an interface in Go?" No. "it's possible to do this a bit more elegantly, perhaps using the reflect package" also no. – Adrian Jan 13 '21 at 14:35

1 Answers1

0

One simple solution is that create a registry package which contain

  1. a map (key as string i.e. name of package and value is function pointer)
  2. a function to fill the data in map.
  3. a function to call the function pointer from map based on package name passed.

In each package, implement init() function that will register the package name with Handler function to register package.

xs2tarunkukreja
  • 446
  • 3
  • 8