7、登陆简单逻辑介绍及实现

登陆简单逻辑介绍及实现

一、实现后端登录接口

7、登陆简单逻辑介绍及实现 - 图1

 

二、知识点

  1. 如何获取前端传递过来的参数如mobile,passwd
  2. 如何返回json到前端

三、代码实战(接上节课代码继续)

1、第一版登录代码

package main

import (
	"net/http"
)

func main() {
	//把前端请求的格式和封装处理函数进行绑定的标签
	//绑定请求和处理函数
	http.HandleFunc("/user/login",
		func(writer http.ResponseWriter,
			request *http.Request) {
			//数据库操作
			//逻辑处理
			//restapi json/xml 返回
			//1.获取前端传递的参数
			//mobile,passwd
			//如何获取参数
			//解析参数
			request.ParseForm()
			mobile := request.PostForm.Get("mobile")
			passwd := request.PostForm.Get("passwd")
			loginOk := false
			if mobile == "xxxxxxxxxx" && passwd == "123456" {
				loginOk = true
			}
			if loginOk {
				//返回json ok
				str := `{"code":0,"data":{"id":1,"token":"test"},"msg":"登录成功}}`
				//设置header 为JSON 默认的text/html,所以特别指出返回的为application/json
				writer.Header().Set("Content-Type", "application/json")
				//设置200状态
				writer.WriteHeader(http.StatusOK)
				//输出
				writer.Write([]byte(str))
			} else {
				//返回失败的JSON
				str := `{"code":-1,"data":"",msg":"密码不正确"}}`
				//设置header 为JSON 默认的text/html,所以特别指出返回的为application/json
				writer.Header().Set("Content-Type", "application/json")
				//设置200状态
				writer.WriteHeader(http.StatusOK)
				//输出
				writer.Write([]byte(str))
			}
			//如何返回JSON
			//io.WriteString(writer, "Hello World!")
		})
	//启动web服务器
	http.ListenAndServe(":8080", nil)
}

2、 第二版代码优化(优化返回Json数据)

 
package main
import (
	"net/http"
)
func main() {
	//把前端请求的格式和封装处理函数进行绑定的标签
	//绑定请求和处理函数
	http.HandleFunc("/user/login",
		func(writer http.ResponseWriter,
			request *http.Request) {
			//数据库操作
			//逻辑处理
			//restapi json/xml 返回
			//1.获取前端传递的参数
			//mobile,passwd
			//如何获取参数
			//解析参数
			request.ParseForm()
			mobile := request.PostForm.Get("mobile")
			passwd := request.PostForm.Get("passwd")
			loginOk := false
			if mobile == "xxxxxxxxxxx" && passwd == "123456" {
				loginOk = true
			}
			str := `{"code":0,"data":{"id":1,"token":"test"},"msg":"登录成功"}`
			if !loginOk {
				//返回失败的JSON
				str = `{"code":-1,"data":"","msg":"密码不正确"}`
			}
			//设置header 为JSON 默认的text/html,所以特别指出返回的为application/json
			writer.Header().Set("Content-Type", "application/json")
			//设置200状态
			writer.WriteHeader(http.StatusOK)
			//输出
			writer.Write([]byte(str))
		})
	//启动web服务器
	http.ListenAndServe(":8080", nil)
}

四、测试登录接口

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值