1、连接postgres数据库的服务端代码:
package main
import (
"database/sql"
"fmt"
"html/template"
"log"
"net/http"
_ "github.com/lib/pq"
)
type authUser struct {
UserLoginName string
UserName string
}
//IndexHandler 首页展示用户信息
func IndexHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
dbUser := "postgres"
dbPass := "mypassword"
dbHost := "localhost"
dbPort := "5432"
dbName := "mydb"
connStr := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", dbHost, dbPort, dbUser, dbPass, dbName)
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal(err)
}
rows, err := db.Query("SELECT USER_LOGIN_NAME,USER_NAME FROM public.AUTH_USER")
if err != nil {
log.Println(err)
}
var authUsers []authUser
for rows.Next() {
var au authUser
rows.Scan(&au.UserLoginName, &au.UserName)
authUsers = append(authUsers, au)
}
t, err := template.ParseFiles("templates/index.html")
if err != nil {
log.Println(err)
}
err = t.Execute(w, authUsers)
if err != nil {
log.Println(err)
}
}
}
func main() {
http.HandleFunc("/", IndexHandler)
fmt.Println("服务端口:8000") //控制台输出信息
err := http.ListenAndServe(":8000", nil) //设置监听的端口
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
2、go语言渲染前端模板代码
<div>
{{.}}
</div>
有疑问加站长微信联系(非本文作者)