dotweb框架之旅 [一] - HelloWorld

一直想着,要系統性的寫一些dotweb使用的文章,以前拖延了很多時間,今天,下定決定,算是正式的開始,也請你們一塊兒監督。html

dotweb,是一款追求簡約大方的go web框架,正如其github項目主頁的自我介紹同樣:Simple and easy go web micro framework」,我相信可以堅持貫徹這一點,給你們提供一個用的舒服用的安心的框架:)git

框架地址:https://github.com/devfeel/dotwebgithub

目錄:web

一、dotweb框架之旅 [一] - HelloWorldapp

二、dotweb框架之旅 [二] - 經常使用對象-App(dotweb)框架

三、dotweb框架之旅 [三] - 經常使用對象-HttpServerpost

 

這一章是開篇,先從著名的「HelloWorld」開始:spa

一、極客版debug

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)
}

二、工程版日誌

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啓動過程分爲幾步:

一、初始化App容器

二、設置工做模式(development\production

三、註冊路由模快

四、設置端口

五、啓動服務

 

以上五個步驟,其中第二步不是必須,默認爲development模式。

 

但願本文能給你們帶來一些幫助。

本文代碼地址:https://github.com/devfeel/dotweb-example/blob/master/helloworld/main.go

歡迎各位加入咱們的go語言QQ羣:193409346

相關文章
相關標籤/搜索