工作需要,掌握了Go语言。
现在正在开发一个网站,此帖为记录Some问题。
一.后端问题:
1.反向代理:
域名A记录绑定主机名,地址定向固定IP,形成二级域名
开启apache proxy模块
root@iZ28sf0466vZ:/etc/apache2/sites-available# a2enmod proxy Module proxy already enabled root@iZ28sf0466vZ:/etc/apache2/sites-available# a2ensite beauty.lenggirl.com.conf Site beauty.lenggirl.com already enabled root@iZ28sf0466vZ:/etc/apache2/sites-available# service apache2 reload * Reloading web server apache2 * root@iZ28sf0466vZ:/etc/apache2/sites-available#
编辑配置文件
root@iZ28sf0466vZ:~# cd /etc/apache2/sites-available/ root@iZ28sf0466vZ:/etc/apache2/sites-available# more beauty.lenggirl.com.conf NameVirtualHost beauty.lenggirl.com:80 <VirtualHost beauty.lenggirl.com:80> # The ServerName directive sets the request scheme, hostname and port th at # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. ServerName beauty.lenggirl.com ServerAdmin webmaster@localhost ProxyRequests Off <Proxy *> Order deny,allow Allow from all </Proxy> ProxyPass / http://127.0.0.1:8080/ ProxyPassReverse / http://127.0.0.1:8080/ # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the # following line enables the CGI configuration for this host only # after it has been globally disabled with "a2disconf". #Include conf-available/serve-cgi-bin.conf </VirtualHost>
2.Go依赖工具
go get github.com/hunterhug/beautyart/Godeps
godep save
godep go
3.Go运维其他方面
4.beego配置
考虑session用redis存储
-
SessionName
设置 cookies 的名字,Session 默认是保存在用户的浏览器 cookies 里面的,默认名是 beegosessionID,配置文件对应的参数名是:sessionname。
-
SessionHashFunc
默认值为sha1,采用sha1加密算法生产sessionid
-
SessionHashKey
默认的key是beegoserversessionkey,建议用户使用的时候修改该参数
当 SessionProvider 为 redis 时,SessionSavePath 是 redis 的链接地址,采用了 redigo,如下所示:
beego.SessionProvider = "redis"
beego.SessionSavePath = "127.0.0.1:6379"
权限控制例子
如下例子所示,验证用户是否已经登录,应用于全部的请求:
var FilterUser = func(ctx *context.Context) { _, ok := ctx.Input.Session("uid").(int) if !ok && ctx.Request.RequestURI != "/login" { ctx.Redirect(302, "/login") } } beego.InsertFilter("/*",beego.BeforeRouter,FilterUser)
路由定义由数据库来实时定义,不需要写配置
var UrlManager = func(ctx *context.Context) { //数据库读取全部的url mapping数据 urlMapping := model.GetUrlMapping() for baseurl,rule:=range urlMapping { if baseurl == ctx.Request.RequestURI { ctx.Input.RunController = rule.controller ctx.Input.RunMethod = rule.method break } } } beego.InsertFilter("/*",beego.BeforeRouter,UrlManager)
但是数据库一乱就呵呵了,以下为模板根据控制器和模板url自动生成
下面是我们注册的路由:
beego.Router("/api/list", &TestController{}, "*:List")
beego.Router("/person/:last/:first", &TestController{})
beego.AutoRouter(&TestController{})
那么通过方式可以获取相应的URL地址:
UrlFor("TestController.List")
// 输出 /api/list
UrlFor("TestController.Get", ":last", "xie", ":first", "asta")
// 输出 /person/xie/asta
UrlFor("TestController.Myext")
// 输出 /Test/Myext
UrlFor("TestController.GetUrl")
// 输出 /Test/GetUrl
默认情况下,beego已经注册了urlfor函数,用户可以通过如下的代码进行模板调用
{{urlfor "TestController.List"}}
package routers import ( "a/controllers" "a/controllers/admin" "github.com/astaxie/beego" ) func init() { beego.Router("/admin", &admin.MainController{}) beego.Router("/", &controllers.MainController{}) }
测试后可以得知 <title>s{{urlfor "admin.MainController.Get"}}s</title> <title>s{{urlfor "controllers.MainController.Get"}}s</title>
同名会根据加载顺序进行覆盖,否则加完整包名。
两个控制器直接传数据
// 显示设置信息 func (c *MainController) Get() { flash:=beego.ReadFromRequest(&c.Controller) if n,ok:=flash.Data["notice"];ok{ //显示设置成功 c.TplName = "set_success.html" }else if n,ok=flash.Data["error"];ok{ //显示错误 c.TplName = "set_error.html" }else{ // 不然默认显示设置页面 c.Data["list"]=GetInfo() c.TplName = "setting_list.html" } } // 处理设置信息 func (c *MainController) Post() { flash:=beego.NewFlash() setting:=Settings{} valid := Validation{} c.ParseForm(&setting) if b, err := valid.Valid(setting);err!=nil { flash.Error("Settings invalid!") flash.Store(&c.Controller) c.Redirect("/setting",302) return }else if b!=nil{ flash.Error("validation err!") flash.Store(&c.Controller) c.Redirect("/setting",302) return } saveSetting(setting) flash.Notice("Settings saved!") flash.Store(&c.Controller) c.Redirect("/setting",302) }
错误自定义
beego 框架默认支持 404、401、403、500、503 这几种错误的处理。用户可以自定义相应的错误处理,例如下面重新定义 404 页面:
func page_not_found(rw http.ResponseWriter, r *http.Request){ t,_:= template.New("404.html").ParseFiles(beego.ViewsPath+"/404.html") data :=make(map[string]interface{}) data["content"] = "page not found" t.Execute(rw, data) } func main() { beego.Errorhandler("404",page_not_found) beego.Router("/", &controllers.MainController{}) beego.Run() }
从1.4.3版本开始,支持Controller方式定义Error错误处理函数,这样就可以充分利用系统自带的模板处理,以及context等方法。
package controllers import ( "github.com/astaxie/beego" ) type ErrorController struct { beego.Controller } func (c *ErrorController) Error404() { c.Data["content"] = "page not found" c.TplName = "404.tpl" } func (c *ErrorController) Error501() { c.Data["content"] = "server error" c.TplName = "501.tpl" } func (c *ErrorController) ErrorDb() { c.Data["content"] = "database is now down" c.TplName = "dberror.tpl" }
通过上面的例子我们可以看到,所有的函数都是有一定规律的,都是Error
开头,后面的名字就是我们调用Abort
的名字,例如Error404
函数其实调用对应的就是Abort("404")
我们就只要在beego.Run
之前采用beego.ErrorController
注册这个错误处理函数就可以了
package main import ( _ "btest/routers" "btest/controllers" "github.com/astaxie/beego" ) func main() { beego.ErrorController(&controllers.ErrorController{}) beego.Run() }
二.前端资源
http://bootswatch.com/paper/ 样式代码
有疑问加站长微信联系(非本文作者)