Tiny Go Web (TGW)是一個很是簡單的Web框架,甚至談不上框架。TGW無心取代任何框架,TGW的誕生是由於做者在使用beego時有種挫敗感,決定本身從新寫一個適合本身網站用的(私人借書網,由於網站沒有完成備案,暫時由託管在US的vps進行反向代理到ucloud主機,訪問可能會有必定的延時),從構思到完成總共只花了一天時間,由於以爲它已經夠用了,就沒有繼續添加新的功能。html
項目地址:http://github.com/icattlecoder/tgwgit
> go get github.com/icattlecoder/tgw > cd src/github.com/icattlecoder/tgw/example > go build > ./example
控制器實現自動路由註冊,例若有如下的結構github
type Server struct { //成員由業務邏輯而定,如mgo的數據庫鏈接信息等 } func NewServer( /*入參,例如從配置文件中讀取*/) *Server { return &Server{} } //對應模板爲index.html ,返回值data用於渲染模板 func (s *Server) Index() (data map[string]interface{}) { data = map[string]interface{}{} author := Author{ Name: "icattlecoder", Email: []string{"icattlecoder@gmail.com", "iwangming@hotmail.com"}, QQ: "405283013", Blog: "http://blog.segmentfault.com/icattlecoder", } data["author"] = author return } //因爲沒有json.html模板,可是卻有data返回值,此data將以json字符串的格式返回 func (s *Server) Json() (data map[string]interface{}) { data = map[string]interface{}{} author := Author{ Name: "icattlecoder", Email: []string{"icattlecoder@gmail.com", "iwangming@hotmail.com"}, QQ: "405283013", Blog: "http://blog.segmentfault.com/icattlecoder", } data["author"] = author return } //這裏根據請求自動解析出args //例如可將 /hello?msg=hello world的函數解析爲TestArgs{Msg:"hello world"} //因爲沒有hello.html模板,而且沒有返回值,能夠經過env中的RW成員寫入返回數據 func (s *Server) Hello(args TestArgs, env tgw.ReqEnv) { env.RW.Write([]byte(args.Msg)) err = env.Session.Set("key", args) if err != nil { log.Println(err) } } func (s *Server) AdminIndex(){}
如下是程序啓動代碼數據庫
func main() { ser := controllers.NewServer() t:=tgw.NewTGW() log.Fatal(t.Register(&ser).Run(":8080")) }
tgw的Register方法會自動註冊如下的路由:json
/hello ===> func (s *Server) Hello(args TestArgs, env tgw.ReqEnv) /index ===> func (s *Server) Index() (data map[string]interface{}) /Json ===> func (s *Server) Json() (data map[string]interface{}) /admin/index ===> func (s *Server) AdminIndex()
即localhost:8080/index
的處理函數是service.Index
,localhost:8080/admin/index
的處理函數是service.AdminIndex
segmentfault
視圖默認放在view文件夾中,其文件名與url有關,例如:/index
對應 view/index.html
若是某個url沒有對應的視圖,可是它的處理函數卻有返回值,那麼將返回對象JOSN序列化的結果。
視圖中能夠經過<include src="<src>" />
指令包含其它文件,如公共頭區域。session
如下面的代碼爲例:框架
type TestArgs struct { Msg string } func (s *Server) Hello(args TestArgs, env tgw.ReqEnv)
對於請求localhost:8080/Hello?msg=Hello world
,tgw將自動根據請求方法(POST或GET)識別並解析出TestArgs變量.
當前可以自動解析的類型有int
、string
、bool
、float64
memcached
tgw自帶*Args
參數解析,即結構名符合*Args
的參數均可以自動解析。若是須要定製解析,實現Parser接口便可函數
框架實現了一個簡單的session管理,基本知足通常的需求,若是須要使用session,處理函數必須有一個類型爲tgw.ReqEnv的參數,經過此函數可訪問Session。另外,Session的值由memcached存儲,所以實際運行時須要一個memecached服務。
若是函數包含類型爲tgw.ReqEnv參數,且無返回值,能夠直接向ReqEnv.RW中寫入返回結果。