代码如下:
package main
import (
"fmt"
"net/http"
)
// http://127.0.0.1:9001/login/?username=admin&password=1234
func login(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域
w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
w.Header().Set("content-type", "application/json") //返回数据格式是json
// 判断参数是否是Get请求,并且参数解析正常
if r.Method == "GET" && r.ParseForm() == nil {
// 接收参数
userName := r.FormValue("username")
fmt.Printf("userName: %s \n", userName)
passWord := r.FormValue("password")
fmt.Printf("passWord: %s \n", passWord)
if userName == "" || passWord == "" {
w.Write([]byte("用户名或密码不能为空"))
}else{
if userName == "admin" && passWord == "1234" {
w.Write([]byte("登录成功!"))
} else {
w.Write([]byte("用户名或密码错误!"))
}
}
}
}
// http://127.0.0.1:9001/
func sayHello(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域
w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
w.Header().Set("content-type", "application/json") //返回数据格式是json
// r.ParseForm()
// fmt.Println("收到客户端请求: ", r.Form)
// 向客户端写数据
_, _ = w.Write([]byte("hello go"))
}
// http://127.0.0.1:9001/work/
func doWork(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域
w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
w.Header().Set("content-type", "application/json") //返回数据格式是json
// r.ParseForm()
// fmt.Println("收到客户端请求: ", r.Form)
// 向客户端写数据
_, _ = w.Write([]byte("{name:\"liming\"}"))
}
func main() {
//1.注册一个处理器函数
http.HandleFunc("/", sayHello)
http.HandleFunc("/work/", doWork)
http.HandleFunc("/login/", login)
//2.设置监听的TCP地址并启动服务
//参数1:TCP地址(IP+Port)
//参数2:handler handler参数一般会设为nil,此时会使用DefaultServeMux。
err := http.ListenAndServe("127.0.0.1:9001", nil)
if err != nil {
fmt.Printf("http.ListenAndServe()函数执行错误,错误为:%v\n", err)
return
}
fmt.Println("helloworld")
}
然后打开浏览器,
输入:http://127.0.0.1:9001/
输入:http://127.0.0.1:9001/work
输入:http://127.0.0.1:9001/login/?username=admin&password=1234