Golang { Syntax int := 7 }

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. 연습문제

이전의 연습에서 당신이 작성한 그림 생성기를 기억하십니까? 다른 생성기를 만들어봅시다.
하지만 이번에는 데이터의 슬라이스 대신에 image.Image 의 구현체를 반환할 것입니다.
당신 자신의 Image 타입을 정의하시고, 필수 함수들 을 구현하신 다음, pic.ShowImage 를 호출하십시오.
Bounds 는 image.Rect(0, 0, w, h) 와 같은 image.Rectangle 을 반환해야 합니다.
ColorModel 은 color.RGBAModel 을 반환해야 합니다.
At 은 하나의 컬러를 반환해야 합니다; 지난 그림 생성기에서 값 v 는 color.RGBA{v, v, 255, 255} 와 같습니다.

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)
}

==== Output ====

글의 문제가 있다면 댓글을 달아 주세요.

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.