I understand that Go doesn't have traditional OOP concepts. However, I'd love to know whether there is a better way for designing a "constructor" as I've done it in my code snippet below:
type myOwnRouter struct {
}
func (mor *myOwnRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello from my own Router!")
}
func newMyOwnRouter() *myOwnRouter {
return &myOwnRouter{}
}
func init() {
http.Handle("/", newMyOwnRouter())
...
}
I basically would like to get rid of the "stand alone" newMyOwnRouter() function and have it as part of the struct itself, for example I'd like to be able to do something like:
http.Handle("/", myOwnRouter.Router)
Is that doable?
The defacto standard pattern is a function calle New
package matrix
function NewMatrix(rows, cols int) *matrix {
m := new(matrix)
m.rows = rows
m.cols = cols
m.elems = make([]float, rows*cols)
return m
}
Of course the construct function must be a Public one, to be called outside of the package.
More about constructor pattern here
In your case looks like you want a Sigleton package then this is the pattern:
package singleton
type myOwnRouter struct {
}
var instantiated *myOwnRouter = nil
func NewMyOwnRouter() * myOwnRouter {
if instantiated == nil {
instantiated = new(myOwnRouter);
}
return instantiated;
}