一直想着,要系統性的寫一些dotweb使用的文章,之前拖延了不少時間,今天,下定決定,算是正式的開始,也請大家一起監督。
dotweb,是一款追求簡約大方的go web框架,正如其github項目主頁的自我介紹一樣:“Simple and easy go web micro framework”,我相信能夠堅持貫徹這一點,給大家提供一個用的舒服用的安心的框架:)
框架地址:https://github.com/devfeel/dotweb
目錄:
2、dotweb框架之旅 [二] - 常用對象-App(dotweb)
3、dotweb框架之旅 [三] - 常用對象-HttpServer
這一章是開篇,先從著名的“HelloWorld”開始:
1、極客版
package main import ( "fmt" "github.com/devfeel/dotweb" ) func main() { //初始化DotServer app := dotweb.New() //注冊hello路由 app.HttpServer.GET("/hello", func (ctx dotweb.Context) error { ctx.WriteString("hello world!") return nil }) //開始服務 port := 8080 err := app.StartServer(port) fmt.Println("dotweb.StartServer error => ", err) }
2、工程版
package main import ( "fmt" "github.com/devfeel/dotweb" ) func main() { //初始化DotServer app := dotweb.New() //開啟debug模式 app.SetDevelopmentMode() //設置路由 InitRoute(app.HttpServer) //開始服務 port := 8080 err := app.StartServer(port) fmt.Println("dotweb.StartServer error => ", err) } func Hello(ctx dotweb.Context) error { ctx.WriteString("hello world!") return nil } func InitRoute(server *dotweb.HttpServer) { server.Router().GET("/hello", Hello) }
以上兩段代碼都是實現一樣的功能,通過訪問http://127.0.0.1:8080/hello 輸出“hello world!”字符串。
極客版:一般僅為演示項目何其簡介的時候才會這么寫,做非常少量的路由時可以這么做,但一般工程項目不建議這么做,會加大維護的難度
工程版:正常項目,請務必剝離路由注冊和HttpHandle的實現
項目版:目前為了盡量減少大家在使用dotweb時候的各種糾結,已經啟動start項目,可以參考真實項目的一些目錄指引 - https://github.com/devfeel/dotweb-start
啟動日志:
訪問http://127.0.0.1:8080/hello請求情況:
至此,成功達成目標。
如HelloWorld代碼,整個Web啟動過程分為幾步:
1、初始化App容器
2、設置工作模式(development\production)
3、注冊路由模快
4、設置端口
5、啟動服務
以上五個步驟,其中第二步不是必須,默認為development模式。
希望本文能給大家帶來一些幫助。
本文代碼地址:https://github.com/devfeel/dotweb-example/blob/master/helloworld/main.go
歡迎各位加入我們的go語言QQ群:193409346