【发布时间】:2016-07-26 07:32:01
【问题描述】:
我需要扩展 http 包以实现包含状态错误描述的非标准响应,即: 400 缺少必需的参数 而不是标准状态描述的 400 Bad request。
这是我的实际实现:
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
)
type GatewayHandler int
func main() {
var gh GatewayHandler
http.ListenAndServe(":9000", gh)
}
func (gh GatewayHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
legacyApiUrl := "http://some-url.com" + req.URL.RequestURI()
client := &http.Client{}
request, _ := http.NewRequest(req.Method, legacyApiUrl, nil)
response, _ := client.Do(request)
res.Header().Set("Status", response.Status)
for k, v := range response.Header {
fmt.Println(k, ": ", v)
i := ""
for _, j := range v {
i += j
}
res.Header().Set(k, i)
}
res.WriteHeader(response.StatusCode)
if response.Status != "200 OK" {
fmt.Println(response.Status)
}
result, _ := ioutil.ReadAll(response.Body)
output := string(result)
fmt.Println(output)
io.WriteString(res, output)
}
一般来说,我需要从使用它的其他 URL 转发该状态,并且我需要保持它兼容。
非常感谢您。
约瑟夫
【问题讨论】:
-
您的具体问题是什么?在您当前的实施中,什么对您不起作用?你想为一些遗留 API 编写代理吗?
-
是的,有点...问题是标题需要像
状态消息应该包含错误描述,但不是标准的,例如 400 Bad request , 但是 400 缺少必需的参数,或者 400 No timestamp in request or so...
标签: http go http-status