在实例中使用Hijack()时http.ResponseWriter
Hijack() (net.Conn, *bufio.ReadWriter, 错误)
read from thenet.Conn和 the 和有*bufio.ReadWriter什么不一样?
我知道我可以使用手动向每个 HTTP 请求添加标头
cli := &http.Client{}
req, err := http.NewRequest("GET", "https://myhost", nil)
req.Header.Add("X-Test", "true")
if err != nil {
panic(err)
}
rsp, err := cli.Do(req)
Run Code Online (Sandbox Code Playgroud)
但我想为我的应用程序中的每个 HTTP 请求自动添加此标头。
最好的方法是什么?
去http pkg提供一个劫持者界面,任何人都可以告诉我什么时候应该使用它.
我检查注释,在Hijack调用允许调用者接管连接后,HTTP服务器库将不会对连接执行任何其他操作.
我理解它,因为它用于在一个端口内支持http请求和公共tcp交互.这样对吗?它有任何其他好处.
我有以下代码:
resp, err = http.Head("http:something.com")
if err != nil {
//do something
}
if resp.StatusCode == http.StatusOK {
// do something
}
Run Code Online (Sandbox Code Playgroud)
由于我没有阅读 的正文,因此resp我假设我不需要像 那样关闭它resp.Body.Close()。我的假设正确吗还是我应该打电话resp.Body.Close()?
我想在Go中下载Fantasy Football Data进行分析,但是当我尝试从这个api页面下载时,我得到了一个空的响应,即使该代码适用于其他网站,例如这个api页面
最小的再现,输出一个空数组.
package main
import (
"fmt"
"io/ioutil"
"net/http"
"time"
)
const AllPlayerData = "https://fantasy.premierleague.com/drf/bootstrap-static"
func main() {
downloadAllData()
}
func downloadAllData() {
client := &http.Client{
Timeout: 20 * time.Second,
}
response, err := client.Get(AllPlayerData)
if err != nil {
fmt.Println("Unable to download player data.")
return
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println("Failed to read response")
return
}
defer response.Body.Close()
fmt.Println(body)
}
Run Code Online (Sandbox Code Playgroud)
相同的网页在Python中下载得很好:
import requests
url = "https://fantasy.premierleague.com/drf/bootstrap-static"
r = requests.get(url) …Run Code Online (Sandbox Code Playgroud) 我尝试启动多个 http 服务器,侦听同一包中的不同端口。在我的测试 HandleFunc 函数中,我需要打印我们的主机和服务请求的 http 服务器的端口信息。我该怎么做呢?
这是我的示例代码:
package main
import (
"encoding/json"
"flag"
"log"
"net/http"
"os"
"github.com/dineshgowda24/lb/backendserver/config"
)
func main() {
c := flag.String("c", "config/config.json", "Please specify conf.json")
flag.Parse()
file, err := os.Open(*c)
if err != nil {
log.Fatal("Unable to open config file")
}
defer file.Close()
decoder := json.NewDecoder(file)
config := bconfig.BackendConfiguration{}
err = decoder.Decode(&config)
if err != nil {
log.Fatal("Unable to decode conf.json file")
}
http.HandleFunc("/", handle)
for _, s := range config.Servers {
log.Printf("Started server at : …Run Code Online (Sandbox Code Playgroud) 我正在使用 net/http 包,想知道如何从代码中的任何位置退出处理程序。假设我有这段代码:
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
func handler(w http.ResponseWriter, r *http.Request){
err := checkSomeThing(w, r)
if err != nil {
return
}
fmt.Println("End of Handler.")
return
}
func checkSomeThing(w http.ResponseWriter, r *http.Request) error{
http.Error(w, "Bad Request!", http.StatusBadRequest)
return errors.New("bad request")
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,我想从 checkSomeThing 函数中退出处理程序,而不必返回,然后再次返回一个级别,随着应用程序的增长,情况会变得更糟。这纯粹是为了代码的可读性。
目录树:
.
??? main.go
??? web
??? app.go
??? views
??? index.html
??? js
??? app.jsx
Run Code Online (Sandbox Code Playgroud)
这有效:
package main
import (
"net/http"
)
func main() {
http.Handle("/", http.FileServer(http.Dir("./web/views")))
http.ListenAndServe(":3000", nil)
}
Run Code Online (Sandbox Code Playgroud)
但这回归404 page not found:
main.go:
package main
import (
"{dir with main.go}/web"
)
func main() {
web.StartHttp()
}
Run Code Online (Sandbox Code Playgroud)
app.go:
package web
import (
"fmt"
"net/http"
)
func StartHttp() {
fmt.Println("STARTHTTP - CHECK 01")
http.Handle("/", http.FileServer(http.Dir("./views")))
http.ListenAndServe(":3000", nil)
}
Run Code Online (Sandbox Code Playgroud)
终端打印STARTHTTP - CHECK 01,因此StartHttp()调用该功能,并且终端要求允许传入的网络连接,因此http服务器似乎正在侦听端口.
是否有某种类型的上下文未传递给其他包?
我正在尝试并行进行 http 查询,然后等待所有查询完成:
g1, _ := go http.Get('http://example.com/1')
g2, _ := go http.Get('http://example.com/2')
res1 := g1.wait() or { panic(err) }
res2 := g2.wait() or { panic(err) }
data1 := json.decode(ApiResult, res1.text) or { panic(err) }
data2 := json.decode(ApiResult, res2.text) or { panic(err) }
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
src/main.go:159:11: syntax error: unexpected go, expecting expression
Run Code Online (Sandbox Code Playgroud) 我想为 params 数组中的每个参数发出一个 get 请求。网址是静态的。有没有办法为每次迭代重用我的自定义 http 客户端?我不想为每个请求重置标头。理想情况下,我想client.Do(param)为每次迭代做类似的事情。
client := &http.Client{}
for _, param := range params {
uri := url + param
req, err := http.NewRequest(http.MethodGet, uri, nil)
req.Header.Add("Cookie", cookie)
resp, _ := client.Do(req)
defer resp.Body.Close()
// do something...
}
Run Code Online (Sandbox Code Playgroud)