英文:
Passing JSON parameter to function in GOLANG
问题
我想将一个 JSON 对象传递给 GOLANG 中的一个函数,那么我应该如何定义我的参数?如果我将参数定义为字符串,是否可以?以下是一个示例:
func getDetailedNameSpace(authentication string, id string) string {
var jsonStr = []byte(string)
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
req, _ := http.NewRequest("PUT", "https://"+authentication.endPoint+"/object/namespaces/"+id, bytes.NewBuffer(jsonStr))
req.Header.Add("X-Sds-Auth-Token", authentication.authtoken)
req.Header.Add("Accept", "application/json")
res, err := client.Do(req)
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Printf("%s", err)
}
return string(body)
}
另外,我需要验证这些参数,就像在 Python 中可以这样做:
def getDetailedNameSpace(authentication, id=None):
assert authentication is not None, "Authentication Required"
希望对你有帮助!
英文:
I want to pass a JSON object to a function in GOLANG ,so how would I define my parameters,would it be fine if I can define my params as string .below is a sample
func getDetailedNameSpace(authentication string,id string) string{
var jsonStr = []byte(string);
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
req, _ := http.NewRequest("PUT", "https://"+authentication.endPoint+"/object/namespaces/"+id, bytes.NewBuffer(jsonStr))
req.Header.Add("X-Sds-Auth-Token",authentication.authtoken)
req.Header.Add("Accept","application/json")
res,err:=client.Do(req)
body, err := ioutil.ReadAll(res.Body)
if err!=nil{
fmt.Printf("%s",err)
}
return string(body);
}
Also i have to validate the params ,as in python we can have like below
def getDetailedNameSpace(authentication,id=None):
assert authentication!=None,"Authentication Required"
答案1
得分: 2
我假设你正在尝试将JSON作为PUT
请求的主体。在这种情况下,你只需要使用赋值操作。请求对象有一个类型为io.ReadCloser
的字段。
req.Header.Add("Accept", "application/json")
req.Body = bytes.NewBufferString(MyJsonAsAString)
res, err := client.Do(req)
还有一些其他的方法,比如http.Post
,它将主体作为参数,但在这种情况下,Do
方法接受一个Request
对象作为参数,该对象有一个Body
属性。
英文:
I'm assuming you're trying to put the JSON as the body of your PUT
request. In this case you'll just want to use assignment. The request object has a field of type io.ReadCloser
for it.
req.Header.Add("Accept","application/json")
req.Body = bytes.NewBufferString(MyJsonAsAString)
res,err:=client.Do(req)
There are some other methods like http.Post
which take the body as an argument but in this case, the Do
method takes a Request
object as an argument and that has a property for the Body
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论