Golang Syntax _7
24. 웹서버
package main import ( "fmt" "net/http" ) type Hello struct{} func (h Hello) ServeHTTP( w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello!") } func main() { var h Hello http.ListenAndServe("localhost:4000", h) }
- Package http는 http.handler를 구현한 어떠한 값을 사용해 HTTP 요청을 제공한다.
- Handler는 다음과 같은 인터페이스를 가진다.
package http type Handler interface { ServeHTTP(w ResponseWriter, r *Request) }
25. 연습문제
아래 나오는 타입을 구현하고 그 타입의 ServeHTTP 메소드를 정의하십시오. 그 메소드를 당신의 웹 서버에서 특정 경로를 처리할 수 있도록 등록하십시오.
type String string
type Struct struct {
Greeting string
Punct string
Who string
}
예컨대, 당신은 아래와 같이 핸들러를 등록할 수 있어야 합니다.
http.Handle("/string", String("I'm a frayed knot."))
http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})
package main import ( "fmt" "net/http" ) type String string func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, s) } type Struct struct { Greeting string Punct string Who string } func (s *Struct) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, s.Greeting, s.Punct, s.Who) } func main(){ http.Handle("/string", String("I'm silnex")) http.Handle("/struct", &Struct{"Hello",":","Gopher!"}) http.ListenAndServe("localhost:4000", nil) }
26. 이미지
package main import ( "fmt" "image" ) func main() { m := image.NewRGBA(image.Rect(0, 0, 100, 100)) fmt.Println(m.Bounds()) fmt.Println(m.At(0, 0).RGBA()) }
- Package Image는 아래와 같은 image인터페이스를 정의한다.
package image type Image interface { ColorModel() color.Model Bounds() Rectangle At(x, y int) color.Color }
27. 연습문제
package main import ( "code.google.com/p/go-tour/pic" "image" "image/color" ) type Image struct{ w, h int colorA, colorB uint8 } func (i *Image) ColorModel() color.Model{ return color.RGBAModel } func (i *Image) Bounds() image.Rectangle { return image.Rect(0,0,i.w,i.h) } func (i *Image) At(x, y int) color.Color{ return color.RGBA{uint8(x), uint8(y), i.colorB, i.colorA} } func main() { m := &Image{123,123,131,141} pic.ShowImage(m) }