선수로 산다, 때론 좋은 코치로
[golang] A Tour of Go - 58 연습 문제 본문
[golang] A Tour of Go - 58 연습 문제
https://go-tour-kr.appspot.com/#58
go 언어로 웹서버 운영은 매우 간단하네요.
type을 설정하고, 타입에 ServeHTTP 메소드를 붙입니다.(A Tour of Go 50번 참조)
http.Handle을 이용하여 핸들러를 등록합니다.
http.ListenAndServe를 이용해서 서비스를 실행하고 Default 페이지를 제공합니다.
아래 나오는 타입을 구현하고 그 타입의 ServeHTTP 메소드를 정의하십시오. 그 메소드를 당신의 웹 서버에서 특정 경로를 처리할 수 있도록 등록하십시오
58번 연습문제는 두개의 핸들러를 등록하는 문제입니다.
하나는 string으로 문자열을 리턴하고, 하나는 구조체와 연결하여 구조체의 문자를 리턴합니다.
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!"})
실행한 후에 브라우저에 localhost:4000을 연결하면 '404 page not found'가 표시됩니다.
localhost:4000/string과 localhost:4000/struct로 연결하세요.
package main
import (
"fmt"
"net/http"
)
type String string
type Struct struct {
Greeting string
Punct string
Who string
}
func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, s)
}
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 a frayed knot."))
http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})
http.ListenAndServe("localhost:4000", nil)
}
'개발 관련 > go' 카테고리의 다른 글
[golang] A Tour of Go - 61 연습 문제 (0) | 2018.02.13 |
---|---|
[golang] A Tour of Go - 60 연습 문제 (0) | 2018.02.13 |
[golang] A Tour of Go - 56 연습 문제 (0) | 2018.02.12 |
[golang] A Tour of Go - 48 연습 문제 (0) | 2018.02.12 |
[golang] A Tour of Go - 44 연습 문제 (0) | 2018.02.01 |
Comments