第一种方式
package main
import (
"net/http"
)
func main() { //db.OpenCon()
http.HandleFunc("/hello", SayHello)
http.ListenAndServe(":8001", nil)
}
func SayHello(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("hello"))
}
运行main程序,网页打开http://localhost:8001/hello
第二种方式:用到第三方包
通过 go get github.com/astaxie/beego 获得包
如果命令行报错,则需下载 git.ext 方可执行
package main
import (
"github.com/astaxie/beego"
)
type HomeController struct {
beego.Controller //默认实现了一些方法 如get post
}
func (this *HomeController) Get() {
this.Ctx.WriteString("Hello world !")
}
func main() {
//注册路由
beego.Router("/", &HomeController{}) //第一个是注册路由地址,为根目录,第二是控制器,根据控制器直接跳转到Get()方法里面去
//注册完毕,可以运行
beego.Run()
}
在未设置端口号的情况下,默认端口号是8080,启动main函数,访问网址http://localhost:8080/