Golang HTTPS / TLS POST客户端/服务器

时间:2016-10-16 17:04:36

标签: post go https

我在Go中编写了一个简单的客户端/服务器,它将通过TLS进行HTTP GET,但我也试图让它能够通过TLS进行HTTP POST。

在下面的示例中,index.html只包含文本hello,并且HTTP GET正常运行。我希望客户端获取HTTP GET并将hello world写回服务器。

客户端

package main

import (
    "crypto/tls"
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
)

func main() {
    link := "https://10.0.0.1/static/index.html"

    tr := &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
    client := &http.Client{Transport: tr}
    response, err := client.Get(link)
    if err != nil {
        fmt.Println(err)
    }
    defer response.Body.Close()

    content, _ := ioutil.ReadAll(response.Body)
    s := strings.TrimSpace(string(content))

    fmt.Println(s)

    // out := s + " world"      
    // Not working POST...
    // resp, err := client.Post(link, "text/plain", &out)

}

服务器

package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/static/", func (w http.ResponseWriter, r *http.Request) {
        fmt.Println("Got connection!")
        http.ServeFile(w, r, r.URL.Path[1:])
    })
    log.Fatal(http.ListenAndServeTLS(":443", "server.crt", "server.key", nil))
}

我目前还没有处理服务器端的POST,但我只是想将它打印到屏幕上,所以当我运行客户端时,我会看到服务器打印hello world

如何修复客户端代码以进行正确的POST?相应的服务器代码应该接受什么样的POST呢?任何帮助将不胜感激,我找不到HTTPS / TLS POST示例。

1 个答案:

答案 0 :(得分:2)

您没有分享错误消息,但我认为client.Post调用不允许将字符串作为其第三个参数,因为它需要io.Reader。试试这个:

out := s + " world"     
resp, err := client.Post(link, "text/plain", bytes.NewBufferString(out))

在服务器端,您已经设置了正确的代码来处理POST请求。只需检查方法:

http.HandleFunc("/static/", func (w http.ResponseWriter, r *http.Request) {
    if r.Method == "POST" {
        // handle POST requests
    } else {
        // handle all other requests
    }
})

我注意到另一个问题。使用index.html可能不会在这里工作。 http.ServeFile将重定向该路径。见https://golang.org/pkg/net/http/#ServeFile

  

作为一种特殊情况,ServeFile会重定向r.URL.Path中的任何请求   结束于" /index.html"走向同一条道路,没有决赛   "的index.html&#34 ;.要避免此类重定向,请修改路径或使用   ServeContent。

我建议只使用不同的文件名来避免这个问题。

相关问题