GO Web Services: Difference between revisions
Jump to navigation
Jump to search
Line 1: | Line 1: | ||
=Handling Requests= | =Handling Requests= | ||
These are the two main ways to handle requests | |||
*Handle a handler to handle requests matching a pattern | *Handle a handler to handle requests matching a pattern | ||
*HandleFunc a function to handle requests matching a pattern | *HandleFunc a function to handle requests matching a pattern | ||
==Handle== | |||
Here is the signature for Handle | |||
<syntaxhighlight lang="go"> | |||
func Handle(pattern string, handler Handler) | |||
</syntaxhighlight> | |||
Handler is an interface which has the signature | |||
<syntaxhighlight lang="go"> | |||
type Handler interface { | |||
ServeHTTP(ResponseWriter, *Request) | |||
} | |||
</syntaxhighlight> | |||
So here is how to use this approach. | |||
<syntaxhighlight lang="go"> | <syntaxhighlight lang="go"> | ||
Revision as of 08:10, 25 August 2021
Handling Requests
These are the two main ways to handle requests
- Handle a handler to handle requests matching a pattern
- HandleFunc a function to handle requests matching a pattern
Handle
Here is the signature for Handle
func Handle(pattern string, handler Handler)
Handler is an interface which has the signature
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
So here is how to use this approach.
type fooHandler struct {
Message string
}
func (f *fooHandler) ServeHTTP(w http.ResponseWrite, r *http.Request) {
w.Write( []byte(f.Message) )
}
func main() {
http.Handle("/foo", &fooHandler{Message: "hello Word"})
}