iris自定義http服務

iris自定義http服務

標籤(空格分隔): iris

代碼示例

main.go

package main
import (
    "net/http"
    "github.com/kataras/iris"
)
func main() {
    app := iris.New()
    app.Get("/", func(ctx iris.Context) {
        ctx.Writef("Hello from the server")
    })
    app.Get("/mypath", func(ctx iris.Context) {
        ctx.Writef("Hello from %s", ctx.Path())
    })
    //這裏有任何自定義字段 Handler和ErrorLog自動設置到服務器
    srv := &http.Server{Addr: ":8080"}
    // http://localhost:8080/
    // http://localhost:8080/mypath
    app.Run(iris.Server(srv)) // 等同於 app.Run(iris.Addr(":8080"))
}

多服務

main.go

package main
import (
    "net/http"
    "github.com/kataras/iris"
)
func main() {
    app := iris.New()
    app.Get("/", func(ctx iris.Context) {
        ctx.Writef("Hello from the server")
    })
    app.Get("/mypath", func(ctx iris.Context) {
        ctx.Writef("Hello from %s", ctx.Path())
    })
    //注意:如果第一個動作是“go app.Run”,則不需要它。
    if err := app.Build(); err != nil {
        panic(err)
    }
    //啓動偵聽localhost:9090的輔助服務器。
    //如果您需要在同一個應用程序中使用多個服務器,請對Listen函數使用“go”關鍵字。
    // http://localhost:9090/
    // http://localhost:9090/mypath
    srv1 := &http.Server{Addr: ":9090", Handler: app}
    go srv1.ListenAndServe()
    println("Start a server listening on http://localhost:9090")
    //啓動一個“second-secondary”服務器,監聽localhost:5050。
    // http://localhost:5050/
    // http://localhost:5050/mypath
    srv2 := &http.Server{Addr: ":5050", Handler: app}
    go srv2.ListenAndServe()
    println("Start a server listening on http://localhost:5050")
    //注意:app.Run完全是可選的,我們已經使用app.Build構建了應用程序,
    //你可以改爲創建一個新的http.Server。
    // http://localhost:8080/
    // http://localhost:8080/mypath
    app.Run(iris.Addr(":8080")) //在這裏以後就不可以監聽了
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章