GO Web Services: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
Line 13: Line 13:
ServeHTTP(ResponseWriter, *Request)
ServeHTTP(ResponseWriter, *Request)
}
}
// Remember we can construct a struct using a struct literal e.g.
type Student struct {
    Name string
    Age  int
}
pb := &Student{ // pb == &Student{"Bob", 8}
    Name: "Bob",
    Age:  8,
}
</syntaxhighlight>
</syntaxhighlight>
So here is how to use this approach. We create a type and implement the interface required.
So here is how to use this approach. We create a type and implement the interface required.
Line 42: Line 30:
func main() {
func main() {
   http.Handle("/foo", &fooHandler{Message: "hello Word"})
   http.Handle("/foo", &fooHandler{Message: "hello Word"})
}
</syntaxhighlight>
'''Remember'''' Remember we can construct a struct using a struct literal e.g.
<syntaxhighlight lang="go">
type Student struct {
    Name string
    Age  int
}
pb := &Student{ // pb == &Student{"Bob", 8}
    Name: "Bob",
    Age:  8,
}
}
</syntaxhighlight>
</syntaxhighlight>

Revision as of 08:20, 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. We create a type and implement the interface required.

// Creating a handler type
type fooHandler struct {
  Message string
}

// Implementing the function for the interface
func (f *fooHandler) ServeHTTP(w http.ResponseWrite, r *http.Request) {
  w.Write( []byte(f.Message) )
}


func main() {
  http.Handle("/foo", &fooHandler{Message: "hello Word"})
}

Remember' Remember we can construct a struct using a struct literal e.g.

type Student struct {
    Name string
    Age  int
}

pb := &Student{ // pb == &Student{"Bob", 8}
    Name: "Bob",
    Age:  8,
}