美文网首页
php登陆接口转 Go

php登陆接口转 Go

作者: HueyYao | 来源:发表于2021-03-11 22:27 被阅读0次

php登陆接口转 Go

转化宗旨:

整理原有接口的请求参数和返回数据信息

分析原有代码了解业务逻辑

不改变请求参数和返回数据的前提下实现功能

登陆接口为例进行操作转换

php流程梳理

路由信息:

//登录接口
Route::post('login/do', 'UserController/loginDo');
//注册接口
Route::post('register/save', 'UserController/saveRegister');

UserController:

    /**
     * 通过手机号和密码登录
     * @param string $mobile
     * @param string $password
     * @return \think\response\Json
     */
    public function loginDo()
    {
        try{
            //获取手机号
            //获取密码
            $mobile = Request::post('mobile', '');
            $password = Request::post('password', '');
            if(!$mobile){
                throw new \Exception("手机号不能为空");
            }
            if(!$password){
                throw new \Exception("密码不能为空");
            }
            if(!isMobile($mobile)){
                throw new \Exception("手机号格式不正确");
            }
            $rs = User::isMobileLogin($mobile, Md5V($password));
            if($rs){
                returnSuccess([
                    'uid' => $rs['id'], 
                    'name' => $rs['name']
                ]);
            }
            throw new \Exception("手机号或密码不正确");
        } catch (\Exception $e) {
            returnError(5000, $e->getMessage());
        }
    }

Model层涉及到的函数isMobileLogin()

    /**
     * 根据手机号和密码获取数据
     * @param string $mobile
     * @param string $password
     * @return rs
     */
    public static function isMobileLogin($mobile, $password){
        $rs = Db::table('user')->where([
            ['mobile', '=', $mobile],
            ['password', '=', $password],
        ])
        ->select();
        if(!$rs->isEmpty()){
            return $rs[0];
        }
        return false;
    }

Common.php涉及到的公共加密函数Md5V()

/**
 * 用户密码MD5方法
 * @param string $password 密码
 * @return json
 */
function Md5V($password){
    return md5($password . 'RaW#XhH2aVgo!Iy1');
}

Common.php返回结果函数:

function returnSuccess($data, $count = 0){
    $return = [
        'code' => 0,
        'items' => $data,
        'count' => $count
    ];
    echo json_encode($return);
    exit;
}

function returnError($code, $msg){
    $return = [
        'code' => $code,
        'msg' => $msg,
    ];
    echo json_encode($return);
    exit;
}

梳理php接口得知登陆接口涉及到的数据有:

**需要传递的参数有:mobile  password**

**需要返回的参数是:uid name**
Go语言写法

在配置好数据库的同时 创建对应路由

func init() {
    beego.Include(&controllers.UserController{})
}

UserController

//用户登录
// @router /login/do [*]
func (this *UserController) LoginDo() {
  //接收参数并赋值
    mobile := this.GetString("mobile")
    password := this.GetString("password")
    //判断数据是否为空
  //ReturnError函数写在公共Common.go文件里
    if mobile == "" {
        this.Data["json"] = ReturnError(4001, "手机号不能为空")
        this.ServeJSON()
    }
    isorno, _ := regexp.MatchString(`^1(3|4|5|7|8)[0-9]\d{8}$`, mobile)
    if !isorno {
        this.Data["json"] = ReturnError(4002, "手机号格式不正确")
        this.ServeJSON()
    }
    if password == "" {
        this.Data["json"] = ReturnError(4003, "密码不能为空")
        this.ServeJSON()
    }
    uid, name := models.IsMobileLogin(mobile, MD5V(password))
    if uid != 0 {
        this.Data["json"] = ReturnSuccess(0, "登录成功", map[string]interface{}{"uid": uid, "username": name}, 1)
        this.ServeJSON()
    } else {
        this.Data["json"] = ReturnError(4004, "手机号或密码不正确")
        this.ServeJSON()
    }
}

Common.go位控制器中的公共函数

package controllers

import (
    "crypto/md5"
    "encoding/hex"
    "time"

    "github.com/astaxie/beego"
)

// Operations about Users
type CommonController struct {
    beego.Controller
}
//定义返回值的struct
type JsonStruct struct {
    Code  int         `json:"code"`
    Msg   interface{} `json:"msg"`
    Items interface{} `json:"items"`
    Count int64       `json:"count"`
}

func ReturnSuccess(code int, msg interface{}, items interface{}, count int64) (json *JsonStruct) {
    json = &JsonStruct{Code: code, Msg: msg, Items: items, Count: count}
    return
}

func ReturnError(code int, msg interface{}) (json *JsonStruct) {
    json = &JsonStruct{Code: code, Msg: msg}
    return
}

//用户密码加密
func MD5V(password string) string {
    h := md5.New()
    h.Write([]byte(password + beego.AppConfig.String("md5code")))
    return hex.EncodeToString(h.Sum(nil))
}

Model层 通过操作数据库来返回结果

//登录功能
func IsMobileLogin(mobile string, password string) (int, string) {
    o := orm.NewOrm()
    var user User
  //找到user表 通过mobile和password来获取一条数据
    err := o.QueryTable("user").Filter("mobile", mobile).Filter("password", password).One(&user)
    if err == orm.ErrNoRows {
        return 0, ""
    } else if err == orm.ErrMissPK {
        return 0, ""
    }
    return user.Id, user.Name
}

相关文章

  • php登陆接口转 Go

    php登陆接口转 Go 转化宗旨: 登陆接口为例进行操作转换 php流程梳理 路由信息: UserControll...

  • Go每日精选(2019-06-14)- 基础部分

    1. Go语言的传参和传引用 2. PHP转Go系列:数组与切片 3. Golang 入门 : channel(...

  • Go语言如何开发RESTful API接口服务

    此前一直写java,最近转go了,总结一下如何用Go语言开发RESTful API接口服务,希望对Go新手有所帮助...

  • php转go学习随笔

    一、 二、相同知识点1、注释方法相同2、变量和常量声明方式一样 var 和const3、运算符基本类似,位运算符记...

  • Golang入门学习路线

    打算PHP转Go,学习了几个月看过各种教程,总结出几个精品的,记录备忘。 Go 入门指南 该文档是 的译文,可以先...

  • golang

    golang go和php的区别类型:go为编译性语言;php解释性语言错误:go的错误处理机制;php本身或者框...

  • 《go web 编程》第四章 访问数据库:database/sq

    Go 与 PHP 不同的地方是 Go 官方没有提供数据库驱动,而是为开发数据库驱动定义了一些标准接口,开发者可以根...

  • Thinkphp自学计划-接口编写-06

    终于到了接口编写了,这是我学PHP一直以来到目的 这次围绕这用户表进行的,主要实现了用户表的4个接口: 注册 登陆...

  • 第04天(面对对象编程)_04

    16_接口的继承.go 17_接口转换.go 18_空接口.go 19_类型断言:if.go 20_类型断言:sw...

  • 玩游戏,赚了一万钻

    go!go!go!转!转!转!眼睛跟着转盘转了N次圈万钻!万钻!万转!唉!又是2个钻! go! go! go!...

网友评论

      本文标题:php登陆接口转 Go

      本文链接:https://www.haomeiwen.com/subject/mlnoqltx.html