36. 웹 서비스 지정 경로에서의 get 매개 변수 수신 및 처리
type dollars float32
디스플레이 형식을 결정하는 String () 방법 만들기
func (d dollars) String() string { return fmt.Sprintf("$%.2f", d) }
맵 사전을 만들어서 여러 가지 물건을 저장하는 가격입니다.
type MyHandler map[string]dollars
http.Handler에서 처리 경로 및 수신 매개 변수 작업
func (self MyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)
전체 코드 예
package main
import (
"fmt"
"net/http"
"log"
)
type dollars float32
func (d dollars) String() string { return fmt.Sprintf("$%.2f", d) }
type MyHandler map[string]dollars
func (self MyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
switch req.URL.Path {
case "/list":
for item, price := range self {
fmt.Fprintf(w, "%s: %s
", item, price)
}
case "/price":
item := req.URL.Query().Get("item")
//item2 := req.Form.Get("item")
price, ok := self[item]
if !ok {
w.WriteHeader(http.StatusNotFound) // 404
fmt.Fprintf(w, "no such item: %q
", item)
return
}
fmt.Fprintf(w, "%s
", price)
default:
w.WriteHeader(http.StatusNotFound) // 404
fmt.Fprintf(w, "no such page: %s
", req.URL)
}
}
func main() {
handler := MyHandler{"shoes": 50, "socks": 5}
log.Fatal(http.ListenAndServe(":4000", handler))
}
프로그램 실행 후 직접 액세스http://localhost:4000/결과는 다음과 같다.
no such page: /
방문http://localhost:4000/list결과는 다음과 같다.
shoes: $50.00
socks: $5.00
방문http://localhost:4000/price결과는 다음과 같다.
no such item: ""
이 경로는 정확한 매개 변수가 필요하기 때문에 접근해야 한다http://localhost:4000/price?item=socks결과는 다음과 같다.
$5.00
http://localhost:4000/price?item=shoes결과는 다음과 같다.
$50.00
이 예는 대부분의 크로스 페이지 전참과 처리의 기본 방식을 해결할 수 있다.만약 자신이 전달한 매개 변수가 주소 표시줄에 나타나기를 원하지 않는다면, 요청한 페이지에post 방법을 사용해야 합니다.물론 수신 페이지도 상응하는 수신 방법을 바꿔야 한다.