go framework bee의 프런트 엔드와 백 엔드 간의 여러 가지 데이터 상호 작용 방법

하나는 얻을 매개 변수를urlquery

  • 1. url유형

    http:xxx:8080/person?name=hell&age=20
    
  • 2. 백엔드에서 라우팅 정의

    func init() {
          
          
        beego.Router("/person", &person.PersonController{
          
          })
    }
    
  • 3. 백엔드에서 매개 변수 가져 오기

    package person
    
    import (
    	"fmt"
    	"github.com/astaxie/beego"
    )
    
    type PersonController struct {
          
          
    	beego.Controller
    }
    
    //定义get请求
    func (c *PersonController) Get() {
          
          
    	//方式一
    	name1 := c.GetString("name")
    	age1 := c.GetString("age")
    	fmt.Println("方式一", name1, age1)
    	//方式二
    	name2 := c.Input().Get("name")
    	age2 := c.Input().Get("age")
    	fmt.Println("方式二", name2, age2)
    	c.TplName = "person.html"
    }
    
    

둘째, 얻을 매개 변수를urlparams

  • 1, 브라우저 url모드

    http:xx:8080/person/10
    
  • 2. 라우팅을 정의 할 때

    func init() {
          
          
        beego.Router("/", &controllers.MainController{
          
          })
        //后端通过接收id的方式来接收数据?:id:int也可以这样,那么只能接收一个int类型的数据
        beego.Router("/person/?:id", &person.PersonController{
          
          })
    }
    
    
  • 3. 컨트롤러에서 데이터 수신

    ** :id**, 직접 작성 하지 마십시오id

    //定义get请求
    func (c *PersonController) Get() {
          
          
    	//方式一
    	id1 := c.GetString(":id")
    	fmt.Println("方式一", id1)
    	
    	//方式二
    	id3 := c.Ctx.Input.Param(":id")
    	fmt.Println("方式三", id3)
      // 方式三,直接接收多个参数,一个map
      params := c.Ctx.Input.Params()
    	c.TplName = "person.html"
    }
    

셋째, 프런트 엔드는 post양식을 사용하여 데이터를 제출합니다.

  • 1. 간단한 form양식 정의

    <form action="/post" method="post">
        <div>
            <label>用户名:</label>
            <input type="text" name="username"/>
        </div>
        <div>
            <label>密码:</label>
            <input type="password" name="password">
        </div>
        <div>
            <button type="submit">提交</button>
        </div>
    </form>
    
  • 2. 라우팅 정의

    func init() {
          
          
      	// get请求会到get中,post请求会到post中
        beego.Router("/post", &post.PostControllers{
          
          })
    }
    
  • 3. 컨트롤러 정의

    package post
    
    import (
    	"fmt"
    	"github.com/astaxie/beego"
    )
    
    type PostControllers struct {
          
          
    	beego.Controller
    }
    
    func (c *PostControllers) Get() {
          
          
      c.TplName = "post.html"
    }
    
    func (c *PostControllers) Post() {
          
          
    	//方式一
    	username := c.GetString("username")
    	password := c.GetString("password")
    	fmt.Println("方式一获取参数", username, password)
    	//方式二
    	username1 := c.Input().Get("username")
    	password1 := c.Input().Get("password")
    	fmt.Println("第二种方式", username1, password1)
    	c.TplName = "test.tpl"
    }
    

넷째, post제출 된 데이터는 구조로 파싱됩니다.

  • 1. 프런트 엔드 정적 코드

    <form action="/post" method="post">
        <div>
            <label>用户名:</label>
            <input type="text" name="username"/>
        </div>
        <div>
            <label>密码:</label>
            <input type="password" name="password">
        </div>
        <div>
            <label>性别:</label>
            <label for="body">
                <input type="radio" name="gender" value="1" id="body"></label>
            <label for="girl">
                <input type="radio" name="gender" value="2" id="girl"></label>
        </div>
        <div>
            <label>价格:</label>
            <input type="text" name="price">
        </div>
        <div>
            <label>是否记住密码</label>
            <input type="checkbox" name="isCheck">
        </div>
        <div>
            <button type="submit">提交</button>
        </div>
    </form>
    
  • 2. 백엔드는 데이터 수신 구조를 정의합니다.

    // 这里使用的是form表单接收的方式,就要定义form,方便前端传递过来的是username,在go语言中使用UserName
    type FormData struct {
          
          
    	UserName string `form:"username"`
    	Password string `form:"password"`
    	Gender int `form:"gender"`
    	Price float64 `form:"price"`
    	IsCheck bool `form:"isCheck"`
    }
    
  • 3. post데이터 요청을 수신하고 구조에 저장

    func (c *PostControllers) Post() {
          
          
    	// 定义一个结构体
    	formData := FormData{
          
          }
    	err := c.ParseForm(&formData)
    	if err != nil {
          
          
    		fmt.Println("解析错误")
    	}
    	fmt.Println(formData)
    	c.TplName ="test.tpl"
    }
    

다섯째, 프런트 엔드 및 백 엔드 json에서 데이터 전달

  • 1. 구성 파일에서 열기

    // conf/app.conf文件中加上这句
    copyrequestbody = true
    
  • 2. 데이터를 수신 할 구조 정의

    //定义一个学生的结构体
    type Student struct {
          
          
    	Name   string `json:"name"`
    	Gender string `json:"gender"`
    	Age    int    `json:"age"`
    }
    
  • 3. 정의 된 post컨트롤러가 데이터를 수신합니다.

    func (c *StudentControllers) Post() {
          
          
    	var student Student
    	data := c.Ctx.Input.RequestBody // 二进制的json数据
    	//将二进制的json解析到结构体中
    	err := json.Unmarshal(data, &student)
    	if err != nil {
          
          
    		fmt.Println("获取数据错误")
    	}
    	fmt.Println(student, "接收的数据")
    	//注意这里必须返回一个map
    	result := map[string]string{
          
          "code": "200", "message": "成功"}
    	c.Data["json"] = result
    	//定义返回json
    	c.ServeJSON()
    }
    
  • 4. postman디버그 인터페이스 사용

추천

출처blog.csdn.net/kuangshp128/article/details/108907601