以beego框架和mux库分别搭建helloworld为例。
一.beego过程
如果使用bee工具初始化项目,则命令行执行:bee new <项目名>;也可不使用bee工具,直接通过go mod。beego项目目录如下:
配置文件 conf/app.conf:
appname = mybeego
httpport = 8089
runmode = dev
控制层 controllers/default.go
package controllers
import (
beego "github.com/beego/beego/v2/server/web"
)
type MainController struct {
beego.Controller
}
type UserController struct {
beego.Controller
}
func (c *MainController) Get() {
c.Ctx.WriteString("helloworld !")
}
func (c *UserController) Get() {
c.Data["Website"] = "beego.me"
c.Data["Email"] = "astaxie@gmail.com"
c.TplName = "index.tpl"
}
路由 routers/router.go
package routers
import (
"mybeego/controllers"
beego "github.com/beego/beego/v2/server/web"
)
func init() {
beego.Router("/", &controllers.MainController{})
beego.Router("/user", &controllers.UserController{})
}
mian.go:
package main
import (
_ "mybeego/routers"
"github.com/beego/beego/v2/server/web"
)
func main() {
web.Run()
}
二.mux+net/http
本例使用第三方路由库mux和go标准库net/http搭建一个简单的helloworld
controller/default.go:
fun GetHello(w http.ResponseWriter, r *http.Request){
w.Write([]byte("helloword!"))
}
router/router.go:
package router
import (
"beezhb/controller"
"github.com/gorilla/mux"
)
var (
Router = mux.NewRouter()
)
func init() {
Router.HandleFunc("/hello", controller.GetHello)
}
main.go:
package main
import (
"beezhb/router"
"net/http"
)
func main() {
server := &http.Server{
Addr: ":8089",
Handler: router.Router,
}
server.SetKeepAlivesEnabled(false)
_ = server.ListenAndServe()
}