beego.md
官方文档 set gopath=D:\goobj;D:\Golang\vendor
设置两个gopath 一个是项目目录的gopath
= https://beego.me/docs/mvc/controller/router.md beego 安装
go get github.com/astaxie/beego
gorm
http://gorm.io/zh_CN/docs/index.html
gcc
http://www.mingw.org/
bee 工具 bee工具可以直接生成项目结构
go get github.com/beego/bee
- 需要配置环境变量 或者临时设置 set PATH=%PATH%;%GOPATH%/bin
new 命令 web应用
api 命令 api应用
bee new testApi
运行项目 项目都依赖 go get github.com/astaxie/beego
bee run
app.conf 配置
appname = testweb
runmode = dev
[dev]
httpport = 8080
[prod]
httpport = 8080
[test]
httpport = 8080
路由配置 router.go
beego.Router("/beego", &controllers.MainController{})
//任何方法访问
beego.Router("/beego", &controllers.MainController{},"*:Index")
beego.Router("/beego", &controllers.MainController{},"post:Index")
beego.Router("/beego", &controllers.MainController{},"put:Index")
beego.Router("/beego", &controllers.MainController{},"delete:Index")
beego.Router("/beego", &controllers.MainController{},"get,post:Index")
beego.Router("/testinput",&controllers.TestinputController{},"get:Get;post:Post")
//测试controller
func (c *MainController)Post() {
c.Ctx.WriteString("this is method post!")
}
controller
继承controller
type MainController struct {
beego.Controller
}
//TestController t 必须大写
type TestController struct {
beego.Controller
}
func (c *TestController) Get() {
c.Data["Website"] = "beego.me" //data数据直接到tpl中
c.Data["Email"] = "astaxie@gmail.com"
c.TplName = "index.tpl" //模板名称
}
func (c *TestController)Post() {
//相当于echo
c.Ctx.WriteString("<font style =\"color:red\">welcome</font>")
//c.Ctx.WriteString("this is method post!")
}
接收参数
//接收参数返回
func (c *TestinputController) Get() {
id :=c.GetString("id")
c.Ctx.WriteString(id)
id :=c.Input().Get("id")
//fmt.Println(id)
c.Ctx.WriteString(id)
}
//ParseForm 接收表单数据
type User struct {
Id string
Name string
}
func (c *TestinputController) Get() {
u :=User{}
if err :=c.ParseForm(&u); err !=nil{
}
c.Ctx.WriteString(" 11 " + u.Id + " 111 "+u.Name)
}
使用RequestBody 接收数据
修改app.conf
copyrequestbody = true
func (c *TestinputController) Get() {
var ob models.Object
json.Unmarshal(c.Ctx.Input.RequestBody,&ob)
objectid := models.AddOne(ob)
c.Data["json"]="{\"ObjectId\" :\"\"\" "+ objectid +"\"}"
c.ServeJSON()
}
cookie session
cookie
func (c *TestinputController) Get() {
name := c.Ctx.GetCookie("name")
password := c.Ctx.GetCookie("password")
if name !=""{
c.Ctx.WriteString("username:"+ name +"password:" +password)
}else{
c.Ctx.WriteString(`<html><form></form></html>`)
}
}
func (c *TestinputController) Post() {
u :=User{}
if err:=c.ParseForm(&u) ; err != nil{
}
c.Ctx.SetCookie("name",u.Username , 100,"/")
c.Ctx.SetCookie("password", u.Password , 100 , "/") //清楚cookie -1
c.Ctx.WriteString("Username:"+ u.Username + "password:" + u.Password)
}
session
//main设置
beego.BConfig.WebConfig.Session.SessionOn=true
//app.conf
sessionon = true
func (c *TestinputController) Get() {
name := c.GetSession("name")
if nameString , ok := name.(string); ok && nameString !=""{
}
}
model
go get github.com/astaxie/beego/orm
go get github.com/go-sql-driver/mysql
type User struct {
Id int
Username string
Password string
}
func (c *TestinputController) Get() {
orm.RegisterDataBase("default","mysql","root:root@tcp(127.0.0.1:3306)/golang?charset=utf8" ,30)
orm.RegisterModel(new(User))
o:=orm.NewOrm()
user :=User{
Username:"zhangsan",
Password:"123456",
}
//插入
id,err :=o.Insert(&user)
c.Ctx.WriteString(fmt.Sprint("%d %v " , id , err))
}
type User struct {
Id int
Username string
Password string
}
func (c *TestinputController) Get() {
orm.RegisterDataBase("default","mysql","root:root@tcp(127.0.0.1:3306)/golang?charset=utf8" ,30)
orm.RegisterModel(new(User))
o:=orm.NewOrm()
user :=User{
Username:"zhangsan",
Password:"222",
}
user.Id=1
//修改
id,err :=o.Update(&user)
c.Ctx.WriteString(fmt.Sprint("%d %v " , id , err))
}
var maps []orm.Params
num,err := o.Raw("Select * from user").Values(&maps)
for _,term :=range maps{
fmt.Println((term["Id"]),":" , term["name"])
}
queryBuilder
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
func (c *TestinputController) Get() {
orm.Debug=true
orm.RegisterDataBase("default","mysql","root:root@tcp(127.0.0.1:3306)/golang?charset=utf8" ,30)
orm.RegisterModel(new(User2))
o:=orm.NewOrm()
var users []User2
qb , _:=orm.NewQueryBuilder("mysql")
qb.Select("Password").From("user").Where("Username = ?").Limit(1)
sql:=qb.String()
o.Raw(sql,"zhangsan").QueryRows(&users)
c.Ctx.WriteString(fmt.Sprintf("user :%v" , users))
}
controller 调用 model
//models代码
package models
import (
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
type User struct {
Id int64
Username string
Password string
}
var(
db orm.Ormer
)
func init() {
orm.Debug=true
orm.RegisterDataBase("default","mysql","root:root@tcp(127.0.0.1:3306)/golang?charset=utf8" ,30)
orm.RegisterModel(new(User))
db = orm.NewOrm()
}
func AddUser(user_info * User)(int64,error) {
id,err := db.Insert(user_info)
return id,err
}
//控制器代码
user := models.User{Username:"admin" , Password:"1235689"}
px,py := models.AddUser(&user)
fmt.Sprint(py)
c.Ctx.WriteString(strconv.FormatInt(px,10))//int64-> string
打包linux 的项目
bee pack -be GOOS=linux
orm
o := orm.NewOrm()
var user []orm.Params
num,err := o.Raw("select * from user limit 2").Values(&user)
fmt.Println(num)
fmt.Println(err)
for k,v:=range user{
fmt.Println(k,v["user_id"] , v["user_name"])
}
return user
打包linux 执行文件
bee pack -be GOOS=linux
解压
tar zxvf framing.tar.gz -C framing
./执行文件
server
{
# 监听 80 端口
listen 10000;
autoindex on;
server_name www.jaydenmall.com;
access_log /usr/local/nginx/logs/access.log combined;
index index.html index.htm index.jsp index.php;
if ( $query_string ~* ".*[\;'\<\>].*" ){
return 404;
}
location / {
# 反向代理到 8080 端口
proxy_pass http://127.0.0.1:12000;
add_header Access-Control-Allow-Origin *;
}
access_log /home/wwwlogs/access.log;
}
nginx 部署
Go 是一个独立的 HTTP 服务器,但是我们有些时候为了 nginx 可以帮我做很多工作,例如访问日志,cc 攻击,静态服务等,nginx 已经做的很成熟了,Go 只要专注于业务逻辑和功能就好,所以通过 nginx 配置代理就可以实现多应用同时部署,如下就是典型的两个应用共享 80 端口,通过不同的域名访问,反向代理到不同的应用。
server {
listen 80;
server_name .a.com;
charset utf-8;
access_log /home/a.com.access.log;
location /(css|js|fonts|img)/ {
access_log off;
expires 1d;
root "/path/to/app_a/static";
try_files $uri @backend;
}
location / {
try_files /_not_exists_ @backend;
}
location @backend {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://127.0.0.1:8080;
}
}
server {
listen 80;
server_name .b.com;
charset utf-8;
access_log /home/b.com.access.log main;
location /(css|js|fonts|img)/ {
access_log off;
expires 1d;
root "/path/to/app_b/static";
try_files $uri @backend;
}
location / {
try_files /_not_exists_ @backend;
}
location @backend {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://127.0.0.1:8081;
}
}
session 存储切片
func (this *MainController) Get2() {
v1 := this.GetSession("UserInfo")
fmt.Printf("%p",v1)
if v1 == nil {
user := make(map[string]string);
user["username"] = "name"
user["usercode"] = "code"
user["num"] = "num"
fmt.Printf("%p",user)
this.SetSession("UserInfo", user)
this.Data["num"] = ""
} else {
v2 := v1.(map[string]string)
v2["num"] = v2["num"] + "rrr"
this.SetSession("UserInfo",v2)
this.Data["num"] = v1
}
fmt.Println(v1,111111111)
this.Data["Website"] = "beego.me"
this.Data["Email"] = "astaxie@gmail.com"
this.TplName = "index.html"
}
对象
func (this *MainController) Get2() {
v1 := this.GetSession("UserInfo")
fmt.Printf("%p",v1)
if v1 == nil {
user := services.User{Username:"1"}
user.Usercode="code"
user.Username="name"
user.Num=1
fmt.Printf("%p",user)
this.SetSession("UserInfo", user)
this.Data["num"] = ""
} else {
fmt.Println(v1)
v2 := v1.(services.User)
v2.Num =v2.Num+1
this.SetSession("UserInfo",v2)
//this.Data["num"] = v
}
this.Data["Website"] = "beego.me"
this.Data["Email"] = "astaxie@gmail.com"
this.TplName = "index.html"
}