Skip to content

Instantly share code, notes, and snippets.

@gianpaolof
Last active December 10, 2019 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gianpaolof/fada9a3fc3fa29fabbe939ca3506b86d to your computer and use it in GitHub Desktop.
Save gianpaolof/fada9a3fc3fa29fabbe939ca3506b86d to your computer and use it in GitHub Desktop.
send/receive json with golang using TLS
//client
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"crypto/tls"
)
func main() {
url := "https://localhost:443/api/v1/trigger"
fmt.Println("URL:>", url)
var jsonStr = []byte(`{"json":"on"}`)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("X-Custom-Header", "myvalue")
req.Header.Set("Content-Type", "application/json")
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
}
//server
package main
import (
// "fmt"
// "io"
"net/http"
"log"
)
func HelloServer(w http.ResponseWriter, req * http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.Write([] byte("This is an example server.\n"))
// fmt.Fprintf(w, "This is an example server.\n")
// io.WriteString(w, "This is an example server.\n")
}
func main() {
http.HandleFunc("/hello", HelloServer)
err: = http.ListenAndServeTLS(":443", "server.crt", "server.key", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment