将JSON参数传递给Golang函数

huangapple go评论72阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年9月25日 04:33:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/32770411.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定