Handler crashed with error runtime error: invalid memory address or nil pointer dereference
最近新接触golang,用的beego框架;遇到一个挺特别的问题,百度、google都没有这样的情况;程序执行creashed ** Handler crashed with error runtime error: invalid memory address or nil pointer dereference ** 网上搜索了一波;都是变量没有实例化或者实例化之后指针没有采用指针调用的方式,亦或全局变量被局部定义了的一些案例。
之前有遇见过
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
//_ "github.com/astaxie/beego/session/mysql" // mysql 存储 session 时启用,需注释上一行 mysql-driver 因为该包已导入了 mysql-driver
_ "liumao801/lmadmin/models"
)
注释里面已经写明了原因 **包 github.com/astaxie/beego/session/mysql 已导入了 github.com/go-sql-driver/mysql 如果再次导入 github.com/go-sql-driver/mysql 就重复了 ** 因为程序只实例化了一次 mysql;第二次导入的 mysql 只定义了,没有实例化(不知道这样的说法是否正确,我是这么理解的) 。
下面看看我这次遇见的问题:
代码如下(错误代码):
controller/TestController.go
package controllers
type TestController struct {
BaseController // BaseController 里面也组合了 beego.Controller
UploadController
}
func (c *TestController) Upload() {
c.LmUpload("upload") // 这里调用公共的上传方法
}
controller/UploadController.go
package controllers
import (
"bytes"
"fmt"
"github.com/astaxie/beego"
"io"
"liumao801/lmadmin/utils"
"mime/multipart"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"time"
)
type UploadController struct {
beego.Controller // 这里也组合 beego.Controller
}
type Sizer interface {
Size() int64
}
const (
LOCAL_FILE_DIR = "static/upload/"
MIN_FILE_SIZE = 1 // bytes
MAX_FILE_SIZE = 5000000 // bytes
IMAGE_TYPES = "(jpg|gif|p?jpeg|(x-)?png)"
ACCEPT_FILE_TYPES = IMAGE_TYPES
EXPIRATION_TIME = 300 // seconds
THUMBNAIL_PARAM = "=s80"
)
var (
imageTypes = regexp.MustCompile(IMAGE_TYPES)
acceptFileTypes = regexp.MustCompile(ACCEPT_FILE_TYPES)
)
type FileInfo struct {
Url string `json:"url,omitempty"`
ThumbnailUrl string `json:"thumbnailUrl,omitempty"`
Name string `json:"name"`
Type string `json:"type"`
Size int64 `json:"size"`
Error string `json:"error,omitempty"`
DeleteUrl string `json:"deleteUrl,omitempty"`
DeleteType string `json:"deleteType,omitempty"`
}
// 检测文件类型是否合法
func (fi *FileInfo) ValidateType() (valid bool) {
if acceptFileTypes.MatchString(fi.Type) {
return true
}
fi.Error = "Filetype not allowed"
return false
}
// 检查文件大小是否合法
func (fi *FileInfo) ValidateSize() (valid bool) {
if fi.Size < MIN_FILE_SIZE {
fi.Error = "File is too small"
} else if fi.Size