loadFile(w http.ResponseWriter, r *http.Request) {
f, h, err := r.FormFile("fileupload")
if err != nil {
panic(err)
}
dirname := "../file/" + h.Filename
file, err := os.Create(dirname)
if err != nil {
panic(err)
}
_, err = io.Copy(file, f)
if err != nil {
panic(err)
}
defer file.Close()
fmt.Println(h)
//w.Write([]byte("upload success"))
//写到 数据库 中
fmt.Println(h.Filename, dirname, h.Size)
MgSess.UploadFile(h.Filename, h.Filename, h.Size)
}
func Lists(w http.ResponseWriter, r *http.Request) {
s, err := MgSess.Lists()
if err != nil {
panic(err)
}
fmt.Println(s)
data, err := json.Marshal(s)
fmt.Println(string(data))
w.Write(data)
}
/*
blog.go
yekai
pdj
*/
package main
import (
"fmt"
"gopkg.in/mgo.v2"
)
type MongoSessin struct {
Session *mgo.Session
}
var MgSess *MongoSessin
type BlogInfo struct {
Title string
Length int64
FileDir string
}
func (m *MongoSessin) Connect(url string) {
session, err := mgo.Dial(url)
if err != nil {
panic(err)
}
m.Session = session
}
func (m *MongoSessin) UploadFile(title, dir string, length int64) error {
fmt.Println("call UploadFile")
table := m.Session.DB("myblog").C("blogs")
return table.Insert(&BlogInfo{title, length, dir})
}
func (m *MongoSessin) Lists() ([]BlogInfo, error) {
fmt.Println("call Lists")
var blogInfos []BlogInfo
err := m.Session.DB("myblog").C("blogs").Find(nil).All(&blogInfos)
return blogInfos, err
}
??以上就是博客系统后端接口的全部内容,再搭配上一套好看的前端界面就可以使用啦。亲自写过golang代码,才会真正的体会到go语言的优点,快来学习吧。
|