我试着用postman作为客户端来测试我的Golang微服务,但是我不能正确地管理响应。当前的情况是我有一个代理服务,它与一个单独的身份验证服务通信来验证用户,如下面的代码所示。
func Authenticate(w http.ResponseWriter, a AuthPayload){
//////Create a json to send to the auth microservice///////
//Marshal the request struct into a json
jsonData,_:=json.Marshal(a)
log.Printf("got jsonm data as %s",jsonData)
//////Call the auth microservice///////
//http://{name of the authentication service in docker-compose}/{name of url we want from the auth service}
request,err := http.NewRequest("POST", "http://authentication-service:8081/authenticateuser",bytes.NewBuffer(jsonData))
if err!=nil{
log.Printf("Broker service couldnt connect to the auth service, %s",err)
return
}
client:=&http.Client{}
response, err := client.Do(request)
if err!=nil{
log.Printf("Broker service client error: , %s",err)
return
}
defer response.Body.Close()
//////Make sure to get back the correct status code///////
if response.StatusCode == http.StatusUnauthorized{
log.Println("Invalid credentials")
return
}else if response.StatusCode != http.StatusOK{
log.Println("Error authenticating user error code ",response.StatusCode)
return
}
//Create a variable we'll read response.body (from auth service ) into
var jsonFromAuthService jsonResponse
//Decode the json from the auth service
err=json.NewDecoder(response.Body).Decode(&jsonFromAuthService)
if err!=nil{
log.Printf("Error decoding json from auth service: , %s",err)
return
}
var payload =jsonResponse{Error: false,Message: "User Authenticated",Data:jsonFromAuthService.Data}
json.Marshal(payload)
}
Postman 给了我状态码200 ok(我知道这意味着请求已经成功发送),但是我想从我的验证服务得到响应,这将是400无效的密码或电子邮件。我如何修改上面的代码从我的验证服务返回状态码,而不是 Postman 的状态码,同时仍然使用 Postman 作为客户端?
1条答案
按热度按时间3j86kqsm1#
您没有发回任何状态代码;所以,当你的代码执行完毕时,它会返回一个200响应,这就是你在Postman中看到的。如果你想在代码的不同点发送其他响应代码,你可以使用
w.WriteHeader
并发送适用的响应代码。