扩展golang的http包

时间:2016-07-26 07:32:02

标签: http go http-status

我需要扩展http包来实现包含错误描述的非标准响应,即: 400缺少必需参数 而不是标准状态描述的400 Bad请求。

这是我的实际实施:

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)
}

一般情况下,我需要从使用它的其他网址转发该状态,我需要保持兼容。

非常感谢你。

的Jozef

1 个答案:

答案 0 :(得分:2)

您可以使用http.Hijacker界面https://golang.org/pkg/net/http/#Hijacker来"劫持" (接管)服务器与客户端的TCP连接,并向其写入自定义响应。以下是对示例https://golang.org/pkg/net/http/#example_Hijacker的修改以返回" 400缺少必需参数"而不是标准的" 400 Bad request"回复客户:

package main

import "net/http"

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        hj, ok := w.(http.Hijacker)
        if !ok {
            http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
            return
        }
        conn, bufrw, err := hj.Hijack()
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        // Don't forget to close the connection:
        defer conn.Close()
        // non-standard HTTP status text and an HTTP header are written;
        // end of the Headers part of the messages is marked by extra \r\n
        bufrw.WriteString("HTTP/1.1 400 Required parameter is missing\r\nContent-Type: text/html; charset=utf-8\r\n\r\n")
        // write the body of the HTTP response message
        bufrw.WriteString("400 Required parameter is missing\n")
        bufrw.Flush()
    })
    http.ListenAndServe(":9000", nil)
}

运行此程序并发送curl请求会产生所需的响应:

$ curl -i http://localhost:9000/
HTTP/1.1 400 Required parameter is missing
Content-Type: text/html; charset=utf-8

400 Required parameter is missing

应该直接扩展它以传播来自旧版API服务器的其他响应。

修改
在示例程序中使用\r\n\r\n根据HTTP消息标准(https://tools.ietf.org/html/rfc7230#section-3)终止HTTP响应的Headers部分;为清晰起见,已分隔WriteString调用HTTP响应的标头和正文。