go系列(二)搭建一个简单的http服务

代码如下:

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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值