我最近开始学习GoLang。我的目标是揭露一个webapi。这应该能够接受一个json对象,并应该响应另一个json对象。我找不到足够的资源来学习如何使这项工作。我非常感谢这方面的任何帮助。我的代码就像下面一样。
func HelloService(res http.ResponseWriter, req *http.Request){
io.WriteString(res,"Welcome to service")
}
func main(){
http.HandleFunc("/", HelloService)
http.ListenAndServe(":8080",nil)
http.HandleFunc("/saveuser", saveUser)
}
func saveUser(res http.ResponseWriter, req *http.Request){
ConfigurationRepository.SaveUser(User) //I want to receive an User object when this service is being consumed
}
答案 0 :(得分:0)
包装" net / http"会有所帮助。例子:
https://github.com/emicklei/go-restful
https://github.com/gin-gonic/gin
这是一个简单的服务,可以帮助您入门:
package main
import (
"github.com/emicklei/go-restful"
"log"
"net/http"
)
type User struct {
Name string
}
func postOne(req *restful.Request, resp *restful.Response) {
newUser := new(User)
err := req.ReadEntity(newUser)
if err != nil {
resp.WriteErrorString(http.StatusBadRequest, err.Error())
return
}
log.Printf("new user: '%v'", newUser)
}
func main() {
ws := new(restful.WebService)
ws.Path("/users")
ws.Consumes(restful.MIME_JSON)
ws.Produces(restful.MIME_JSON)
ws.Route(ws.POST("").To(postOne).
Param(ws.BodyParameter("User", "A User").DataType("main.User")))
restful.Add(ws)
http.ListenAndServe(":8080", nil)
}
以下是通过发布单个用户来测试服务的卷曲:
curl -v -H "Content-Type: application/json" -XPOST "localhost:8080/users" -d '{"name": "Joe"}'