用golang代理REST API

3

我正在学习 Golang 并尝试在另一种语言中创建的 Rest API 上实现代理。

目前,我只想查询我的 Golang API,提取实际路径参数并基于它查询其他 API。

我希望结果“完全”相同(或至少是主体部分),就像一个简单的 JSON。

目前,我不想为我的数据创建结构,我只想简单地获取和检索内容。

这是我所拥有的:

package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/mux"
)

const API_URL string = "https://my-api-path/"

func setHeaders(w http.ResponseWriter) {
    w.WriteHeader(http.StatusOK)
    w.Header().Set("Content-Type", "application/json")
}

func extractParams(r *http.Request) map[string]string {
    return mux.Vars(r)
}

func getHandler(w http.ResponseWriter, r *http.Request) {
    setHeaders(w)
    params := extractParams(r)

    url := API_URL + params["everything"]
    response, err := http.Get(url)

    if err != nil {
        fmt.Fprint(w, err)
    }

    fmt.Fprint(w, response)

}

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/{everything}", getHandler)
    http.ListenAndServe(":8080", router)
}

我的问题

目前,我无法从其他API检索JSON信息。 我只有一个奇怪的text/plain Content-Type,因为我强制执行了application/json,而且我在响应体中只有一些头部详细信息,类似于:

&{200 OK 200 HTTP/2.0 2 0 map[Allow:[GET, HEAD, OPTIONS] Expect-Ct:[max-age=86400, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"] Server:[cloudflare] Cf-Ray:[some-ray] Date:[Tue, 12 Jun 2018 14:38:57 GMT] Content-Type:[application/json] Set-Cookie:[__cfduid=lolol; expires=Wed, 12-Jun-19 14:38:56 GMT; path=/; domain=some-domain; HttpOnly; Secure] Vary:[Accept-Encoding Cookie] X-Frame-Options:[SAMEORIGIN] X-Xss-Protection:[1; mode=block]] 0xc4201926f0 -1 [] false true map[] 0xc420150800 0xc4200e8370}

您有没有想过如何代理这个请求(或JSON结果)?


2
尝试使用io.Copy(w, response.Body)。请关闭响应体,即defer response.Body.Close()。另外,当Get返回错误并将其写入响应时,没有理由也写入一个nil响应,因此请在if err != nil ...条件语句的末尾添加一个返回语句。 - mkopriva
1个回答

5
关于响应中没有写入Content-Type头部的问题:
由于您执行这些操作的顺序,这似乎是可以预料的:
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")

请看这里:https://golang.org/pkg/net/http/#ResponseWriter 更改头信息映射,除非已修改的标头是尾随标头,否则在调用WriteHeader(或Write)后无效。
尝试将其倒置以阅读:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)

谢谢,这解决了我问题中的 Content-Type 部分 :D - mfrachet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接