我正在学习 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结果)?
io.Copy(w, response.Body)
。请关闭响应体,即defer response.Body.Close()
。另外,当Get返回错误并将其写入响应时,没有理由也写入一个nil响应,因此请在if err != nil ...
条件语句的末尾添加一个返回语句。 - mkopriva