goweb-06-综合示例
从简单的http服务到一个动态网站
- 基本http服务
package main
import (
	"net/http"
)
func main() {
	// 注册路由
	http.HandleFunc("/", Index)
	// 监听端口提供服务
	http.ListenAndServe(":8080", nil)
}
// 处理函数
func Index(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte(""Server RUN"))
}

2. 查询数据库输出
配套数据库为 news_new.sql
package main
import (
	"net/http"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)
func main() {
	// 注册路由
	http.HandleFunc("/", Index)
	// 监听端口提供服务
	http.ListenAndServe(":8080", nil)
}
// 处理函数
func Index(w http.ResponseWriter, r *http.Request) {
	// 连接数据库
	db, _ := sqlx.Open(`mysql`, `root:root@tcp(127.0.0.1:3306)/news?charset=utf8mb4&parseTime=true`)
	mod := &Class{}
	err := db.Get(mod, "select * from class where id =1")
	if err != nil {
		w.Write([]byte(err.Error()))
	}
	w.Write([]byte(mod.Name))
}
//Class db class
type Class struct {
	Id   int
	Name string
	Url  string
}


Comments