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,golang)