当我们使用go建立了服务器,那么一种常见的需求就摆在面前。如何给这个服务器的某个路径传递参数呢?我们研究一下URL传参的接收与处理。
对于http.Request发出的请求,我们需要使用到URL.Query().Get(“XXX”)
实例
首先建立一个 dollars 类型,用以保存货币数值。
type dollars float32
对dollars建立一个String()方法,用以确定显示格式
func (d dollars) String() string { return fmt.Sprintf("$%.2f", d) }
建立一个map字典,保存多种东西的价格。
type MyHandler map[string]dollars
在http.Handler中处理路径和接收参数的操作
func (self MyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)
完整代码示例
package mainimport ("fmt""net/http""log")type dollars float32func (d dollars) String() string { return fmt.Sprintf("$%.2f", d) }type MyHandler map[string]dollarsfunc (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\n", 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) // 404fmt.Fprintf(w, "no such item: %q\n", item)return}fmt.Fprintf(w, "%s\n", price)default:w.WriteHeader(http.StatusNotFound) // 404fmt.Fprintf(w, "no such page: %s\n", 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.00socks: $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

