更新之后的目录结构

在这里插入图片描述

controllers/api/hello.go

package api
import (
	"github.com/gin-gonic/gin"
	"net/http"
	"main/models"
)
func HelloIndex(c *gin.Context) {
	models.GetValue("2")
	c.HTML(http.StatusOK, "api/hello.html", gin.H{})
}

manage/hello.go

package manage

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"main/models"
)

func HelloIndex(c *gin.Context) {
	models.GetValue("2")
	c.HTML(http.StatusOK, "manage/hello.html", gin.H{})
}

models/db.go

package models

import (
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	"log"
)

var db *sql.DB

func InitDB(dataSourceName string) {
	var err error
	db, err = sql.Open("mysql", dataSourceName)

	if err != nil {
		log.Fatal("Error")
	}

	//defer db.Close()
}

models/kv.go

package models

type KV struct {
	Id         int
	Key        string
	Value      string
	Updated_at string
}

func GetValue(key string) (*KV, error) {
	var kv KV
	err := db.QueryRow("SELECT id, `key`, value, updated_at FROM kv where id = ?",
		key).Scan(&kv.Id, &kv.Key, &kv.Value, &kv.Updated_at)
	if err != nil {
		panic(err.Error()) // proper error handling instead of panic in your app
	}

	db.Exec(`update kv 
		set value = value + 1, updated_at = now() 
		where id = ?`, key)

	return &kv, err
}

views/api/hello.html

{{define "api/hello.html"}}

    <div>middle222</div>

{{end}}

views/manage/hello.html

{{define "api/hello.html"}}
    <div>middle222</div>
{{end}}

main.go

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	// "github.com/joho/godotenv"
	// "log"
	// "os"
	"main/controllers/api"
	"main/controllers/manage"
	"main/models"
)

func main() {
	// err := godotenv.Load("../.env")
	// if err != nil {
	// 	log.Fatal("Error loading .env file")
	// }
	// db_database := os.Getenv("DB_DATABASE")
	// db_username := os.Getenv("DB_USERNAME")
	// db_password := os.Getenv("DB_PASSWORD")
	// db_host := os.Getenv("DB_HOST")
	// db_port := os.Getenv("DB_PORT")


	db_database := "test"
	db_username := "root"
	db_password := "root"
	db_host := "127.0.0.1"
	db_port := "3306"
	models.InitDB(fmt.Sprintf("%s:%[email protected](%s:%s)/%s?charset=utf8mb4&timeout=5000ms",
		db_username, db_password, db_host, db_port, db_database))

	router := gin.Default()
	router.LoadHTMLGlob("views/**/*")
	//router.LoadHTMLGlob("views/*.html")
	router.Static("/go/public", "./public")
	router.GET("/hello", api.HelloIndex)
	router.GET("/hello_manage", manage.HelloIndex)
	router.Run() //listen and serve on 0.0.0.0:8080
}