runtime error: invalid memory address or nil pointer dereference
来源:4-3 Iris框架入门---快速入门案例
szuxxy
2019-11-17
package model
type Movie struct {
Name string
}
package repository
import "imooc/model"
type MovieRepository interface {
GetMovieName() string
}
type MovieManager struct {
}
func NewMovieManager() MovieRepository {
return &MovieManager{}
}
func (m *MovieManager) GetMovieName() string {
return "《这是一个挑食的可爱胖子》"
//数据操作,模拟。
movie:=&model.Movie{Name:"《这是一个挑食的可爱胖子》"}
return movie.Name
}
package service
import (
"fmt"
"imooc/repository"
)
type MovieService interface {
ShowMovieName() string
}
type MovieServiceManger struct {
repo repository.MovieRepository
}
func NewMovieServiceManger(repo repository.MovieRepository) MovieService {
return &MovieServiceManger{repo:repo}
}
func (m *MovieServiceManger) ShowMovieName() string {
fmt.Println("视频的名称为:"+m.repo.GetMovieName())
return "我们获取到的视频名称为:"+m.repo.GetMovieName()
}
package controller
import (
"github.com/kataras/iris"
"github.com/kataras/iris/mvc"
"imooc/repository"
"imooc/service"
)
type MovieController struct {
Ctx iris.Context
}
func (c *MovieController) Get() mvc.View{
movieRepository:=repository.NewMovieManager()
movieService:=service.NewMovieServiceManger(movieRepository)
movieRes:=movieService.ShowMovieName()
return mvc.View{
Name:"movie/index.html",
Data:movieRes,
}
}
<h2>{{.}}</h2>
package main
import (
"github.com/kataras/iris"
"github.com/kataras/iris/_examples/mvc/overview/web/controllers"
"github.com/kataras/iris/mvc"
)
func main() {
//1.创建实例及日志级别和注册视图
app:=iris.New()
app.Logger().SetLevel("debug")
app.RegisterView(iris.HTML(".web/view","html"))
//2.注册控制器
mvc.New(app.Party("/hello")).Handle(new(controllers.MovieController))
//3.启动服务
app.Run(
iris.Addr("localhost:8088"),
)
}
报了个这么个错,查了下各种说法太多。好像也定位不到是哪行代码出了错。应该怎么定位到是哪行代码出错呢?
[HTTP Server] http: panic serving 127.0.0.1:65322: runtime error: invalid memory address or nil pointer dereference
正确解法:
注册控制器的代码和相关的import。
package main
import (
"github.com/kataras/iris"
"github.com/kataras/iris/mvc"
"irisdemo20191120/web/controller"
)
func main() {
app := iris.New()
app.Logger().SetLevel("debug")
//加载模板文件
app.RegisterView(iris.HTML("./web/view", ".html"))
// 注册控制器
mvc.New(app).Handle(new(controller.MovieController))
app.Run(
//开启web服务
iris.Addr("localhost:8080"),
// 按下CTRL / CMD + C时跳过错误的服务器:
iris.WithoutServerError(iris.ErrServerClosed),
//实现更快的json序列化和更多优化:
iris.WithOptimizations,
)
}
原来错误的是这样的:
正确的是这样的:
写回答
1回答
-
Cap
2019-11-18
同学 service 和repository 貌似没有实例化。
012019-11-20
相似问题