一、简介
这里简单介绍在go中,http服务的使用。
二、使用
直接上代码,示例如下:
package main
import (
“io”
“net/http”
)
func main() {
//指定路径下的处理器
http.HandleFunc(“/”, httpHandler)
//指定监听host和port
http.ListenAndServe(“localhost:7002”, nil)
}
//http处理器
func httpHandler(rw http.ResponseWriter, req *http.Request) {
//获取参数
vars := req.URL.Query()
println(“id : “, vars.Get(“id”))
//不同子路径,不同返回结果
switch req.URL.Path {
case “/hello”:
io.WriteString(rw, “hello”)
case “/home”:
io.WriteString(rw, “home”)
default:
io.WriteString(rw, “default”)
}
}
浏览器中输入地址: 即可查看效果