第一个beego应用搭建、布署,post+form

新手学习beego框架,搭建了一个最简单的应用。

注意:这个应该是搭建在bee2.0的版本上,不同的版本之间有些写法会有一些差异。

一、环境搭建

环境搭建大家可以参考以下这篇文章

beego+go的环境搭建-CSDN博客

二、产品功能

主要实现看图猜电影简单功能

效果图

三、代码实现

1、models部分 guess.go

package models

import (
	"strings"

	"github.com/beego/beego/v2/client/orm"
)

type Guess struct {
	Id      int64
	Image   string `orm:"size(128)"`
	Content string `orm:"size(128)"`
	Answer  string `orm:"size(128)"`
}

func init() {
	orm.RegisterModel(new(Guess))
}

// GetGuessById retrieves Guess by Id. Returns error if
// Id doesn't exist
func GetGuessById(id int64) (v *Guess, err error) {
	o := orm.NewOrm()
	v = &Guess{Id: id}
	if err = o.QueryTable(new(Guess)).Filter("Id", id).RelatedSel().One(v); err == nil {
		return v, nil
	}
	return nil, err
}


func Answer(sid int, answerkey string) bool {
	subject, err := GetGuessById(int64(sid))

	if err != nil {
		return  false
	}
	return strings.Compare(strings.ToUpper(answerkey), subject.Answer) == 0
}

2、controller部分  default.go

package controllers

import (
	"encoding/json"
	"myproject/models"

	"github.com/beego/beego/v2/core/logs"
	beego "github.com/beego/beego/v2/server/web"
)

type MainController struct {
	beego.Controller
}

// @router / [get]
func (c *MainController) Get() {
	var guess *models.Guess

	// 获取id参数
	id, err := c.GetInt("id")
	if err != nil {
		id = 1   // 如果没有传入id,默认从第一个开始
	}

	// 通过id参数查询model获取数据
	guess, err = models.GetGuessById(int64(id))
	if err != nil {
		c.Ctx.WriteString("guess not exist")
		return
	}

	var option map[string]string
	if err = json.Unmarshal([]byte(guess.Content), &option); err !=
		nil {
		c.Ctx.WriteString("wrong params, json decode")
		return
	}

	c.Data["ID"] = guess.Id
	c.Data["Option"] = option
	c.Data["Image"] = guess.Image
	c.TplName = "guess.tpl"
}

// @router / [post]
func (c *MainController) Post() {
	var guess *models.Guess

	id, err := c.GetInt("id")
	// 记录提交的参数日志
	logs.Info(id)

	if err != nil {
		id = 1
	}
	guess, err = models.GetGuessById(int64(id))
	if err != nil {
		c.Ctx.WriteString("guess not exist")
		return
	}

	answer := c.GetString("key")
	right := models.Answer(id, answer)

	c.Data["Id"] = id
	c.Data["Next"] = guess.Id + 1
	c.Data["Right"] = right
	c.TplName = "guess.tpl"
}

3、view部分-guess.tpl

<!DOCTYPE html>

<html>
<head>
  <title>Beego</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <link rel="shortcut icon" href="/static/img/guess.png" type="image/x-icon" />

  <style type="text/css">
    *,body {
      margin: 0px;
      padding: 0px;
    }

    html,body {
      height: 100%;
    }

    body {
      margin: 0px;
      font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
      font-size: 14px;
      line-height: 20px;
      background-color: #fff;
      display: flex;
      flex-direction: column;
    }

    main {
      display: flex;
      flex-grow: 1;
      flex-direction: column;
      justify-content: center;
      text-align: center;
    }

    a {
      color: #444;
      text-decoration: none;
    }

    label {
      display: block;
    }

    input {
      margin: 10px;
    }

    .img-wrapper {
      margin: 20px 0px;
    }

    .options {
      width: 140px;
      margin: 0 auto;
      text-align: left;
    }

    button {
      margin: 20px 0px;
      padding: 8px 20px;
      border-radius: 6px;
    }

    button.next {
      width: 120px;
    }
  </style>
</head>

<body>
<!--   <header>
  </header> -->
  <main>
    <!-- 处理答题结果 begin -->
    {{if .Next }}
      <div class="img-wrapper">
      {{if .Right}}
          <img src="http://localhost:8080/static/img/4.gif" width=320px>
          <div>
              <button class="next" onclick="location.href='http://localhost:8080/?id={{.Next}}'" type="button">下一个</button>
          </div>
      {{else}}
          <img src="http://localhost:8080/static/img/3.jpg" width=320px>
          <div>
              <button class="next" onclick="location.href='http://localhost:8080/?id={{.ID}}'" type="button">再试一次</button>
          </div>
      {{end}}
      </div>


      <!-- 处理答题结果 end -->
    {{else}}
          <!-- 展示答题信息 begin -->
        <div class="img-wrapper">
            <img src="http://localhost:8080{{.Image}}" width="320px">
        </div>

        <form action="http://localhost:8080/" method="POST">
            <div class="options">
            {{range $key, $value := .Option}}
                <label><input type="radio" name="key" value="{{$key}}">{{$value}}</label>
            {{end}}
            </div>

            <button type="submit">go</button>
            <input type="hidden" name="id" value="{{.ID}}">
        </form>
    {{end}}



    <!-- 展示答题信息 end -->

  </main>
  <script src="/static/js/reload.min.js"></script>
</body>
</html>

4、路由  

package routers

import (
	"myproject/controllers"

	beego "github.com/beego/beego/v2/server/web"
)

func init() {
	 beego.Include(&controllers.MainController{})
}

5、main.go

package main

import (

	_ "myproject/routers"


	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	beego "github.com/beego/beego/v2/server/web"
	_ "github.com/go-sql-driver/mysql" // 注意此行必须加
)

func init() {
	orm.RegisterDriver("mysql", orm.DRMySQL)
	_ = orm.RegisterDataBase("default", "mysql", "root:root@tcp(localhost:3306)/beego?charset=utf8")
	logs.SetLogger("console")

}

func main() {
	beego.Run()
}

四、打包和布署

打包命令  bee pack。 可以根据不同的环境打不同的包

运行 启动

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nbv12589

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值