Last active
December 10, 2019 16:33
-
-
Save gianpaolof/fada9a3fc3fa29fabbe939ca3506b86d to your computer and use it in GitHub Desktop.
send/receive json with golang using TLS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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