This time I will bring you a detailed explanation of the separation of front-end and back-end development using Golang+Nodejs. What are the things to note? Let’s take a look at the following practical cases. 1. Back-end server writes
code:
package mainimport ( "github.com/hprose/hprose-golang/rpc"//<===hprose "fmt" "database/sql" _ "github.com/go-sql-driver/mysql"//<===mysql驱动 "log")func checkErr(err error) { if err != nil { panic(err) } } func mysqlTestConnect(str string) string{//数据库查询 fmt.Print(str) db, err := sql.Open("mysql", "root:换成你数据库的密码@tcp(localhost:3306)/test") if err != nil { log.Fatalf("Open database error: %s\n", err) } defer db.Close() err = db.Ping() checkErr(err) rows, err := db.Query("SELECT * FROM t_test") checkErr(err) var tmp string="" for rows.Next() { var id int var name string rows.Columns() err = rows.Scan(&id, &name) checkErr(err) tmp=tmp+"id:"+string(id)+" name:"+name+"<br/>" } return tmp } func main(){ server := rpc.NewTCPServer("tcp4://0.0.0.0:10010/")//创建服务具体 server.AddFunction("客户端调用函数名", mysqlTestConnect)//添加访问函数 server.Start()//启动}
2. Front-end server writes
code:
const koa = require('koa');//这里以koa 框架为例const app = new koa();var hprose = require("hprose");//hprosevar client = hprose.Client.create("tcp4://127.0.0.1:10010/", ['客户端调用函数名']);//创建客户端连接app.use(function* () { var dt= yield new Promise(function (resolve) { client.客户端调用函数名("请求参数", function (result) { resolve(result); }) }); this.type = 'text/html;charset=utf-8'; this.body = dt; }); app.listen(3000);
3. Effect
Browser access 127.0.0.1:3000 address
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related matters on the php Chinese website article!
Related reading:
What is the difference between python3 and JSHow to make an image upload preview component in H5How to use s-xlsx to import and export Excel filesjs/css dynamic loading of JS plug-insThe above is the detailed content of Detailed explanation of the separation of front-end and back-end development of Golang+Nodejs. For more information, please follow other related articles on the PHP Chinese website!