如何在POST方法中传递标头?

时间:2018-12-12 03:47:10

标签: security go oauth-2.0 http-headers

这里我有一个功能,其中我发送一个POST请求,该请求用于将客户保存在数据中,并使用variable_name.Header.Set()通过Authentication设置标头 但是在身体反应中,它总是会给我以下错误:-

"errors":[
     {"category":"AUTHENTICATION_ERROR",
      "code":"UNAUTHORIZED",
      "detail":"Your request did not include an `Authorization` http header with an access token. }]}

但是在功能中,我设置了身份验证令牌。

代码:-

func CreateCustomer(c *gin.Context) {
customer := models.Customer{}
bearer := strings.Split(c.Request.Header["Authorization"][0], "Bearer")// token pass in the postman.
bearerToken := strings.TrimSpace(bearer[1])

customerErr := json.NewDecoder(c.Request.Body).Decode(&customer)
if customerErr != nil {
    fmt.Println(customerErr)
    return
}
fmt.Println(customer)
bindData, err := json.Marshal(customer)
if err != nil {
    panic(err)
}
var jsonStr = []byte(string(bindData))
url :="https://connect.squareup.com/v2/customers"
fmt.Println(url)

req, err := http.Post(url, "application/json", bytes.NewBuffer(jsonStr))
// I used this one too.
// req.Header.Set("Authorization", "Bearer "+bearerToken)
// req.Header.Set("Accept", "application/json")
req.Header.Add("Authorization", "Bearer "+bearerToken)
req.Header.Add("Accept", "application/json")
fmt.Println(req.Header)
if err != nil {
    panic(err)
}
defer req.Body.Close()
body, _ := ioutil.ReadAll(req.Body)
fmt.Println("response Body:", string(body))
}

type Customer struct {
  GivenName    string   `json:"given_name" bson:"given_name"`
  FamilyName   string   `json:"family_name" bson:"family_name"`
  CompanyName  string   `json:"company_name" bson:"company_name"`
  Nickname     string   `json:"nickname" bson:"nickname"`
  EmailAddress string   `json:"email_address" bson:"email_address"`
  Address      Addresss `json:"address" bson:"address"`
  PhoneNumber  string   `json:"phone_number" bson:"phone_number"`
  ReferenceId  string   `json:"reference_id" bson:"reference_id"`
  Note         string   `json:"note" bson:"note"`
}

req.Header的结果是:-

map[X-Xss-Protection:[1; mode=block] 
    Keep-Alive:[timeout=60] 
    Accept:[application/json] 
    X-Permitted-Cross-Domain-Policies:[none] 
    Content-Type:[application/json] 
    Vary:[Origin, Accept-Encoding] 
    X-Content-Type-Options:[nosniff] 
    X-Download-Options:[noopen] 
    X-Frame-Options:[SAMEORIGIN] 
    Date:[Wed, 12 Dec 2018 03:41:16 GMT] 
    Strict-Transport-Security:[max-age=631152000] 
    Authorization:[Bearer YOUR_TOKEN HERE]]

任何人都可以告诉我,我应该做什么错误,或者我应该在哪里做更正,以便能够在Squareup中节省客户?

1 个答案:

答案 0 :(得分:3)

您的代码发送POST请求,请求处理后,它将标头添加到响应结构:

  

响应,错误:= http.Post(URL,“ application / json”,bytes.NewBuffer(jsonStr))

您应该先设置标头,然后再发送请求:

// create request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
if err != nil {
   panic(err)
}

// set headers
req.Header.Add("Authorization", "Bearer "+bearerToken)
req.Header.Add("Accept", "application/json")

// send request with headers
client := &http.Client{}
response, err := client.Do(req)