您的位置:首页 > 其它

web服务器指定路径下的get参数接收与处理

2018-02-13 10:25 375 查看
    当我们使用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 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\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) // 404
fmt.Fprintf(w, "no such item: %q\n", item)
return
}
fmt.Fprintf(w, "%s\n", price)
default:
w.WriteHeader(http.StatusNotFound) // 404
fmt.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.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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐