http.ResponseWriter as pointer or value?

438 views
Skip to first unread message

Nguyên Nguyễn Văn Cao

unread,
Apr 28, 2012, 6:24:22 AM4/28/12
to golan...@googlegroups.com
Sure this is a newbie stupid question, but I hope some one can give me more detail!
I have a simple code that in defaultHandler it call sub handler Test1 and Test2 as below:
___________________________
func defaultHandler(w http.ResponseWriter, r *http.Request) {
Test1(&w)
Test2(w)
}

func main() {
http.HandleFunc("/", defaultHandler)
http.ListenAndServe(":8080", nil)
}

func Test1(w* http.ResponseWriter) {
fmt.Fprintf(*w, "test1")
}

func Test2(w http.ResponseWriter) {
fmt.Fprintf(w, "test2")
}
___________________________
w http.ResponseWriter is a Interface? And "w" is a instance of an Interface???
In my case, Test function should recive a pointer or a copy of "w"? Why?

Shaban Naasso

unread,
Apr 28, 2012, 8:16:57 AM4/28/12
to golan...@googlegroups.com
interface means simply that it implements all the functions that are declared in the interface

so these are the functions in the interface

type ResponseWriter interface {
    Header() Header
    Write([]byte) (int, error)
    WriteHeader(int)
}
if something implements these 3 functions then it can be used for ResponseWriting
one other detail to help you understand it.

the Write([]byte) (int, error) function you see is actually a function in the io.Writer interface
this means it's a ResponseWriter and also an io.Writer and you can use it for all things you can use these types for.
if you are interested in what this actually means take a look at this post it explains quite nicely how you can work with io to add gzip handling to a http.ResponseWriter's output

Shaban Naasso

unread,
Apr 28, 2012, 8:37:00 AM4/28/12
to golan...@googlegroups.com
after reading my post i thought i try to explain that interface thing better look at following example:

type Fighter interface{
 Fight() bool //finding out if all consitions are met to actually fight
}

type Rebel struct{
 Idelogy string
}

type Mercenary struct{
 Payment int
}

func(r *Rebel)Fight()bool{
 // will fight if he is inclined to do so
 return r.Ideology=="Militaristic"
}

func(m *MercenaryFight()bool{
 // will fight if he gets more than 2000 Dollar 
 return m.Payment > 2000
}

func WillHeFight(fs Fighter)bool{
 return fs.Fight()
}

this is not a complete Program it's just to see how an arbitrary data structure by implementing functions can be used as a certain type
in this case Fighter.

Nguyên Nguyễn Văn Cao

unread,
Apr 28, 2012, 9:06:06 AM4/28/12
to golan...@googlegroups.com
Thank Shaban Naasso for your explanation about interface :)

Vào 19:37:00 UTC+7 Thứ bảy, ngày 28 tháng tư năm 2012, Shaban Naasso đã viết:
Reply all
Reply to author
Forward
0 new messages