分享
  1. 首页
  2. 文章

Golang开发画室网站记录本

nima · · 2782 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

工作需要,掌握了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运维其他方面

https://lei-cao.gitbooks.io/beego-in-action/content/zh/05.CI-%E6%8C%81%E7%BB%AD%E9%9B%86%E6%88%90.html

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/ 样式代码


有疑问加站长微信联系(非本文作者)

本文来自:博客园

感谢作者:nima

查看原文:Golang开发画室网站记录本

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
2782 次点击
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏