dtsnx44260 2019-02-26 19:54
浏览 104

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

I'm writing a simple webserver in golang that gets/creates/edits/deletes a simple text file. 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. 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. Help appreciated.

  • 写回答

1条回答 默认 最新

  • drfm55597 2019-02-26 20:08
    关注

    The client code is not executed. The callhttp.ListenAndServe(":8080", r) runs the server. The function only returns when there was an error running the server. If the function does return, then log.Fatal will exit the process.

    One fix is to run the server in a goroutine. This will allow main goroutine to continue executing to the client code.

    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.

    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. The example in the documentation show show to use the test server.

    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)