Go实现RESTful_API
Posted 黑荔枝、
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Go实现RESTful_API相关的知识,希望对你有一定的参考价值。
Go实现RESTful_API
下载安装第三方安装包:
go get -u github.com/gorilla/mux
cd $GOPATH/src/github.com/kongyixueyuan.com/education/web
修改/webServer.go
原代码:
```go
func WebStart(app controller.Application)
fs:= http.FileServer(http.Dir("web/static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
// 指定路由信息(匹配请求)
http.HandleFunc("/", app.LoginView)
http.HandleFunc("/login", app.Login)
http.HandleFunc("/loginout", app.LoginOut)
http.HandleFunc("/index", app.Index)
http.HandleFunc("/help", app.Help)
http.HandleFunc("/addEduInfo", app.AddEduShow) // 显示添加信息页面
http.HandleFunc("/addEdu", app.AddEdu) // 提交信息请求
http.HandleFunc("/queryPage", app.QueryPage) // 转至根据证书编号与姓名查询信息页面
http.HandleFunc("/query", app.FindCertByNoAndName) // 根据证书编号与姓名查询信息
http.HandleFunc("/queryPage2", app.QueryPage2) // 转至根据身份证号码查询信息页面
http.HandleFunc("/query2", app.FindByID) // 根据身份证号码查询信息
http.HandleFunc("/modifyPage", app.ModifyShow) // 修改信息页面
http.HandleFunc("/modify", app.Modify) // 修改信息
http.HandleFunc("/upload", app.UploadFile)
fmt.Println("启动Web服务, 监听端口号为: 9000")
err := http.ListenAndServe(":9000", nil)
if err != nil
fmt.Printf("Web服务启动失败: %v", err)
修改后:
func WebStart(app controller.Application)
router := mux.NewRouter()
router.HandleFunc("/education", app.AddUser).Methods("POST")
// 指定路由信息(匹配请求)
fmt.Println("启动Web服务, 监听端口号为: 9000")
err := http.ListenAndServe(":9000", router)
if err != nil
fmt.Printf("Web服务启动失败: %v", err)
cd $GOPATH/src/github.com/kongyixueyuan.com/education/web/controller
修改AddEdu()函数
原代码:
func (app *Application) AddEdu(w http.ResponseWriter, r *http.Request)
edu := service.Education
Name:r.FormValue("name"),
Gender:r.FormValue("gender"),
Nation:r.FormValue("nation"),
EntityID:r.FormValue("entityID"),
Place:r.FormValue("place"),
BirthDay:r.FormValue("birthDay"),
EnrollDate:r.FormValue("enrollDate"),
GraduationDate:r.FormValue("graduationDate"),
SchoolName:r.FormValue("schoolName"),
Major:r.FormValue("major"),
QuaType:r.FormValue("quaType"),
Length:r.FormValue("length"),
Mode:r.FormValue("mode"),
Level:r.FormValue("level"),
Graduation:r.FormValue("graduation"),
CertNo:r.FormValue("certNo"),
Photo:r.FormValue("photo"),
app.Setup.SaveEdu(edu)
//ShowView(w, r, "addEdu.html", data)
r.Form.Set("certNo", edu.CertNo)
r.Form.Set("name", edu.Name)
app.FindCertByNoAndName(w, r)
修改后:
func (app *Application) AddEdu(w http.ResponseWriter, r *http.Request)
var edu service.Education
_ = json.NewDecoder(r.Body).Decode(&edu)
app.Setup.SaveEdu(edu)
fmt.Println(edu)
启动网络:
cd $GOPATH/src/github.com/kongyixueyuan.com/education/fixture
docker-compose up -d
编译:
go build
启动服务:
./education
测试:
curl localhost:9000/education -X POST -d '"Name":"111"'
以上是关于Go实现RESTful_API的主要内容,如果未能解决你的问题,请参考以下文章