기타
go - web 따라해보기(1)
카멜레온개발자
2021. 12. 12. 00:09
유튜브 보고 따라 친건데, 다음과 같이 하면 브라우저에서 저 문구들을 볼 수 있다(포트번호는 3000번)
더보기
더보기
package main
import (
"fmt"
"net/http"
)
type fooHandler struct{}
func (f *fooHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello Foo!")
}
//핸들러 함수를 등록할 수 있다
func barHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello Bar!")
}
func main() {
//어떤 경로의 요청이 들어왔을 때
//어떤 일을 할 것인지
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
//fmt.Fprint : writer에 출력하라
fmt.Fprint(w, "Hello World")
})
http.HandleFunc("/bar", barHandler)
http.Handle("/foo", &fooHandler{})
http.ListenAndServe(":3000", nil)
}
서버 포트를 열어야 하므로 다음과 같이 보안 관련 다이얼로그가 뜨긴 한다
* http객체 대신 mux를 이용하여 똑같은 기능(아직 왜 다른지는 모름)
package main
import (
"fmt"
"net/http"
)
type fooHandler struct{}
func (f *fooHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello Foo!")
}
func barHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello Bar!")
}
func main() {
//어떤 경로의 요청이 들어왔을 때
//어떤 일을 할 것인지
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
//fmt.Fprint : writer에 출력하라
fmt.Fprint(w, "Hello World")
})
mux.HandleFunc("/bar", barHandler)
mux.Handle("/foo", &fooHandler{})
http.ListenAndServe(":3000", mux)
}
* http 클라이언트 request의 argument를 받아서 처리
func barHandler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
if name == "" {
name = "Empty"
}
fmt.Fprintf(w, "Hello %s!", name)
}