Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
向使用Golang接受json和/或参数的第三方公开webapi_Go - Fatal编程技术网

向使用Golang接受json和/或参数的第三方公开webapi

向使用Golang接受json和/或参数的第三方公开webapi,go,Go,我最近开始学咕噜。我的目标是公开一个webapi。这应该能够接受一个json对象,并用另一个json对象响应。我没有找到足够的资源来学习如何让它工作。我真的很感谢你在这方面的帮助。我的一段代码如下所示 func HelloService(res http.ResponseWriter, req *http.Request){ io.WriteString(res,"Welcome to service") } func main(){ http.HandleFunc("/", Hell

我最近开始学咕噜。我的目标是公开一个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
}

包装“net/http”的http包将非常有用。示例:

以下是一个简单的服务,让您开始:

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:

curl -v -H "Content-Type: application/json" -XPOST "localhost:8080/users" -d '{"name": "Joe"}'

你好,妮可,谢谢你的回复。实例ws的所有方法(path、consumes、Products、Route、POST、To、Param、BodyParameter、DataType)都未被识别,但是创建ws时没有错误。与req相同的问题。并非所有方法都得到认可。重启IDE后可能会出现什么问题?很高兴听到这个消息。您使用的是哪个IDE?