Skip to content

net/http: avoid casting and extra function calling (http.HandleFunc, http.DefaultServeMux.HandleFunc) #25706

Closed
@ntrrg

Description

@ntrrg

Looking at the net/http package I notice that HandleFunc and ServeMux.HandleFunc have a func(ResponseWriter, *Request) as parameter instead of HandlerFunc, this means that this functions need to call one extra fuction and an explicit casting respectively.

So if they are written in this way, it can be avoided:

HandleFunc

Since HandlerFunc implements the Handler interface, DefaultServeMux.HandleFunc should be replaced by DefaultServeMux.Handle.

From:

func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
  DefaultServeMux.HandleFunc(pattern, handler)
}

To:

func HandleFunc(pattern string, handler HandlerFunc) {
  DefaultServeMux.Handle(pattern, handler)
}

ServeMux.HandleFunc

Since the handler argument is implicitly casted (or something else happens here?), an explicit casting is not necessary.

From:

func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
  if handler == nil {
    panic("http: nil handler")
  }
  mux.Handle(pattern, HandlerFunc(handler))
}

To:

func (mux *ServeMux) HandleFunc(pattern string, handler HandlerFunc) {
  if handler == nil {
    panic("http: nil handler")
  }

  mux.Handle(pattern, handler)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions