Skip to content

proposal: Go 2: decorator support, like python decorator #36669

Closed
@liamylian

Description

@liamylian

Decorator may make writing GoLang projects more efficient. I hope GoLang support some kind of decorator.

// decorator `Default` sets default value to a int variable
func (intVar *int) @Default(value int) {
	if intVar == nil || *intVar == 0 {
		intVar = &value
	}
}

// decorator `Route` adds route to a `HandlerFunc`
func (handler http.HandlerFunc) @Route(method, uri string) {
	http.HandleFunc(uri, handler)
}

@Route(method = http.MethodGet, uri = "/books/:id") // decorator `Route` run right after function `getBook` is defined. That is, `getBook.Route(http.MethodGet, "/books/:id")` will be called right after function `getBook` is defined. 
func getBook(w http.ResponseWriter, r *http.Request) error {
	return nil
}

func main() {
	@Default(value = 80) // `httpPort.Default(80)` will be called right after variable `httpPort` is initialized 
	var httpPort int

	http.ListenAndServe(fmt.Sprintf(":%d", httpPort), nil)
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions