4-6作业

来源:4-6 本阶段练习题

只为编程

2019-08-02

详细代码
dataModel/Student.go

定义Student结构体

package dataModel

type Student struct {
	ID int
	Name string
	Age int
	Sex int
}

repositories/studentRepository.go

获取student的数据,此处是假数据,正常应该是从库中获取

package repositories

import "iris-introduce/dataModel"

type StudentRepository interface {
	GetStudentInfo() dataModel.Student
}

type StudentManager struct {
}

func NewStudentManager() StudentRepository {
	return &StudentManager{}
}

func (s *StudentManager) GetStudentInfo() dataModel.Student {
	student := dataModel.Student{
		ID:   1,
		Name: "Jack",
		Age:  19,
		Sex:  0,
	}
	return student
}

service/StudentService.go

获取数据,将数据传递到controller层

package services

import (
	"iris-introduce/repositories"
)

type StudentService interface {
	ShowStudentInfo() map[string]interface{}
}

type StudentServiceManager struct {
	StudentRepo repositories.StudentRepository
}

func NewStudentServiceManager(s repositories.StudentRepository) StudentService {
	return &StudentServiceManager{StudentRepo: s}
}

func (s *StudentServiceManager) ShowStudentInfo() map[string]interface{} {
	info := make(map[string]interface{})
	student := s.StudentRepo.GetStudentInfo()
	info["ID"] = student.ID
	info["Name"] = student.Name
	info["Age"] = student.Age
	info["Sex"] = student.Sex
	return info
}

web/controllers/studentController.go

StudentController

package controllers

import (
	"github.com/iris/mvc"
	"iris-introduce/repositories"
	"iris-introduce/services"
)

type StudentController struct {
}

func (s *StudentController) Get() mvc.View {
	studentRepo := repositories.NewStudentManager()
	info := services.NewStudentServiceManager(studentRepo)
	return mvc.View{
		Name: "/student/index.html",
		Data: info.ShowStudentInfo(),
	}
}

web/views/student/index.html

页面展示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Student</title>
</head>
<body>
    <h2>Name: {{.Name}} </h2>
    <h2>ID: {{.ID}} </h2>
    <h2>Age: {{.Age}} </h2>
    <h2>Sex: {{if eq .Sex 0}} 男 {{else if eq .Sex 1}} 女 {{end}}</h2>
</body>
</html>

main.go

增加新的路由

mvc.New(app.Party("/student")).Handle(new(controllers.StudentController))

最后感谢老师,由于我的网络问题。没能把iris的源码包下载完全,导致运行会报框架级别的错误,折腾了几天,老师帮我解决了。谢谢老师!

写回答

1回答

Cap

2019-08-02

nice!

0
0

全流程开发 GO实战电商网站高并发秒杀系统

运用架构设计与系统化思维,从容应对不同流量等级的“秒杀”场景

1462 学习 · 443 问题

查看课程