简体   繁体   English

如何在golang中将http请求发送到我自己的服务器

[英]how to send http request in golang to my own server

I'm writing a simple webserver in golang that gets/creates/edits/deletes a simple text file. 我在golang中编写了一个简单的网络服务器,该服务器获取/创建/编辑/删除一个简单的文本文件。 I've written the function handlers and I'd like to test them by sending a request to the appropriate url and checking to see what happens. 我已经编写了函数处理程序,我想通过将请求发送到适当的url并进行检查以查看会发生什么来对其进行测试。 My code is as below: 我的代码如下:

func createHandler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    name := vars["name"]
    body, _ := ioutil.ReadAll(r.Body)
    fmt.Fprint(w, name)
    ioutil.WriteFile(name, []byte(body), 0644)
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/textFiles/{name}", createHandler).Methods("POST")
    log.Fatal(http.ListenAndServe(":8080", r))

    var url = "http://localhost:8080/textFiles/testFile.txt"
    var text = []byte(`{"title":"this is an example."}`)
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(text))
    if err != nil {
        panic(err)
    }

    client := &http.Client{}
    client.Do(req)
}

Once this code is run, however, no new file is created. 但是,一旦运行此代码,就不会创建新文件。 I've been googling but I can't find anything on this type of problem, where I'm sending a request to the server that I'm building within the same file. 我一直在使用Google搜索,但是在这种类型的问题上我什么都找不到,我正在向正在同一文件中构建的服务器发送请求。 Help appreciated. 帮助表示赞赏。

The client code is not executed. 客户端代码未执行。 The call http.ListenAndServe(":8080", r) runs the server. 调用http.ListenAndServe(":8080", r)运行服务器。 The function only returns when there was an error running the server. 该函数仅在运行服务器时出错时返回。 If the function does return, then log.Fatal will exit the process. 如果函数确实返回,则log.Fatal将退出该过程。

One fix is to run the server in a goroutine. 一种解决方法是在goroutine中运行服务器。 This will allow main goroutine to continue executing to the client code. 这将允许主goroutine继续执行至客户端代码。

go func() {
    log.Fatal(http.ListenAndServe(":8080", r))
}()

This may not fix the problem because there's no guarantee that server will run before the client makes the request. 这可能无法解决问题,因为无法保证服务器会在客户端发出请求之前运行。 Fix this issue by creating the listening socket in the main function and running the server in a goroutine. 通过在主函数中创建侦听套接字并在goroutine中运行服务器来解决此问题。

ln, err := net.Listen("tcp", ":8080")
if err != nil {
    log.Fatal(err)
}
go func() {
    log.Fatal(http.Serve(ln, r))
}()
... client code as before

If the goal if this code is testing, then use httptest.Server . 如果目标是测试此代码,则使用httptest.Server The example in the documentation show show to use the test server. 文档中的示例显示使用测试服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM