2016-10-16 74 views
2

我已經在Go中編寫了一個簡單的客戶端/服務器,它將通過TLS完成HTTP GET,但我也試圖使其能夠通過TLS進行HTTP POST。Golang HTTPS/TLS 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)) 
} 

我現在也沒有什麼可處理在服務器端的職位,但我只是希望它打印出來到屏幕上,所以當我運行客戶端我會看到服務器打印hello world

我應該如何解決我的客戶端代碼來執行正確的POST?相應的服務器代碼應該如何接受POST?任何幫助將不勝感激,我無法找到HTTPS/TLS POST示例。

+0

您需要將證書的CA添加到您的交通工具中[like](http://stackoverflow.com/a/38825553/2604529) –

+0

@MarcelNovy我正在使用自簽名證書......那並不是'跟我的問題沒有任何關係。 – vesche

+0

如果您提到您當前在POST上的嘗試不起作用,這將會很有用。 – superfell

回答

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.htm」明明給相同的路徑結尾的任何請求,沒有最終 「的index.html」。爲避免此類重定向,請修改路徑或使用服務內容。

我建議只使用不同的文件名來避免這個問題。

+0

非常感謝! – vesche