Installing the BEE Tool

The installation

go get github.com/beego/bee
Copy the code

Verify that the installation is successful

cmd 
bee
Copy the code

Create the Beego project

Initialize the project

bee new beegodemo01
Copy the code

Generate the Go Mod configuration file

go mod init beegodemo01
Copy the code

Run the project

bee run
Copy the code

Project file structure

A newgoodsrouting

controllers

// controllers/goods.go package controllers import ( beego "github.com/beego/beego/v2/server/web" ) type GoodsController  struct { beego.Controller } func (c *GoodsController) Get() { c.Data["Website"] = "beego.me" c.Data["Email"] = "[email protected]" c.TplName = "goods.tpl" }Copy the code

router

//routers/router.go

package routers

import (
	"beegodemo01/controllers"
	beego "github.com/beego/beego/v2/server/web"
)

func init() {
    beego.Router("/", &controllers.MainController{})
	beego.Router("/goods", &controllers.GoodsController{})
}

Copy the code

view

//views/goods.tpl <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> </head> <body> <p> </body> </ HTML >Copy the code

Get the reference

// routers/router.go

beego.Router("/article/edit", &controllers.ArticleController{},"get:EditArticle")
Copy the code
// controllers/article. Go func (c *ArticleController) EditArticle() { C. tx.WriteString(" Edit news --"+id)}Copy the code

Post by value

router

// routers/router.go

	beego.Router("/user/edit", &controllers.UserController{},"get:EditUser")
	beego.Router("/user/doEdit", &controllers.UserController{},"post:DoEditUser")
Copy the code

controllers

//controllers/user.go func (c *UserController) EditUser() { c.TplName = "userEdit.html" } type User struct { Username string `form:"username" json:"username"` Password string `form:"password" json:"password"` Hobby []string `form:"hobby" json:"h"` } func (c *UserController) DoEditUser() { u := User{} if err := c.ParseForm(&u); err ! Printf("%#v",u) c.tx.WriteString(" parse post data successfully ")}Copy the code

view

// views/userEdit.html

    <form action="/user/doEdit" method="post">
        <div>
            <span>id</span>
            <input type="text" name='id'>
        </div>
        <div>
            <span>用户名</span>
            <input type="text" name='username'>
        </div>
        <div>
            <span>密码</span>
            <input type="password" name="password">
        </div>
        <div>
            <span>爱好</span>

            <input type="checkbox" value=1 id='label1' name='hobby'><label for='lable1'>吃饭</label>
            <input type="checkbox" value=2 id='label2' name='hobby'><label for='lable2'>睡觉</label>
            <input type="checkbox" value=3 id='label3' name='hobby'><label for='lable3'>打豆豆</label>
        </div>
        <input type="submit" value='提交'>
    </form>
Copy the code

Return JSON data

router

//routers/router.go

	beego.Router("/user/getUser", &controllers.UserController{},"get:GetUser")

Copy the code

controllers

//controllers/user.go type User struct { Username string `form:"username" json:"username"` Password string `form:"password" json:"password"` Hobby []string `form:"hobby" json:"h"` } func (c *UserController) GetUser() { u := User {Username: "zhang", Password: "123456", the Hobby: [] string, {" 1 ", "2"}} c.D c.s. erveJSON ata [" json "] = u ()}Copy the code

The value of map implements the null interface

C.data ["json"] = map[string]interface{}{"code":500," MSG ":" comment error, please try again "} c.servejson ()Copy the code

The config configuration

Configuration file Settings, obtain

// conf/app.conf

mysqluser = "aaa"
admin ="admin","lisi"
Copy the code
// controllers/default.go mysqluser,err := beego.AppConfig.String("mysqluser") if err ! = nil{ return } fmt.Print(mysqluser) admin,err := beego.AppConfig.Strings("admin") if err ! = nil{ return } fmt.Printf("%v %T",admin,admin)Copy the code

set get

beego.AppConfig.Set("redisuser","admin666") redisuser,err := beego.AppConfig.String("redisuser") if err ! = nil{ return } fmt.Print(redisuser)Copy the code

cookie

// controllers/default.go

c.Ctx.SetCookie("username","aa")
Copy the code
// controllers/goods.go
username := c.Ctx.GetCookie("username")
c.Data["username"] = username
Copy the code

The loglog

Beego1. x has Beego. ingo, 2.0 doesn’t

The main method

// main.go

package main

import (
	_ "beegodemo01/routers"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/beego/beego/v2/core/logs"
	"fmt"
)

func main() {
	logs.Info("hello, world-------11")
	logs.SetLogger("file",`{"filename":"logs/test.log"}`)
	beego.Run()
}

Copy the code

The log file

//  logs/test.log
Copy the code

File upload

router

// routers/router.go
beego.Router("/upload", &controllers.UploadController{})
beego.Router("/upload/doUpload", &controllers.UploadController{},"post:DoUpload")
Copy the code

controllers

// controllers/upload.go import ( beego "github.com/beego/beego/v2/server/web" "fmt" "time" ) func (u *UploadController) DoUpload() {// get the uploaded file f,h,_ := u.getfile ("file") defer f.close () fmt.println (h.filename) // Save the uploaded file time_UNIX := time.Now().Unix() fmt.Println(time_unix) file_path := fmt.Sprintf("%d_%s",time_cnix,h.Filename) U. scavetofile ("file","upload/"+file_path) // u.tx.WriteString(" uploaded successfully ") U.ata ["json"] = Interface map [string] {} {" code ": 200," MSG ":" uploaded successfully} "u.S erveJSON ()}Copy the code

views

// html <form action="/upload/doUpload" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <br> < form type="submit" value=" submit" >Copy the code
//ajax <form> <input type="file" id="upload_file"> <br> <input type="button" value=" upload 1" id=" BTN "> </form> <script> var btn = document.getElementById("btn"); btn.onclick = function (ev) { var formdata = new FormData(); console.log($("#upload_file")); formdata.append("file", $("#upload_file")[0].files[0]); $.ajax({ url: "/upload/doUpload", type: "POST", data: formdata, contentType: false, processData: false, success: function (data) { alert(data["msg"]) }, fail: function (data) { } }) } </script>Copy the code

Folder to store

// upload
Copy the code

Beego replacement

Set it in the root directory go.mod