new file go/l18.go for learning http POST requests
This commit is contained in:
parent
6b40418917
commit
edb119f389
2 changed files with 46 additions and 0 deletions
45
go/l18.go
Normal file
45
go/l18.go
Normal file
|
|
@ -0,0 +1,45 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
// "os"
|
||||||
|
// "github.com/joho/godotenv"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
"bytes"
|
||||||
|
"log"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Send struct{
|
||||||
|
Name string `json:"name"`
|
||||||
|
Age int `json:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
fmt.Println("Name for body")
|
||||||
|
var name string
|
||||||
|
fmt.Scanln(&name)
|
||||||
|
data := Send{
|
||||||
|
Name: name,
|
||||||
|
Age: 66,
|
||||||
|
}
|
||||||
|
client := &http.Client{
|
||||||
|
Timeout: 10 * time.Second,
|
||||||
|
}
|
||||||
|
body, err := json.Marshal(data)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("%v\n", err)
|
||||||
|
}
|
||||||
|
req, err := http.NewRequest("POST", "https://api.restful-api.dev/objects", bytes.NewBuffer(body))
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("%v\n", err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("%v\n", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
fmt.Println("Status code", resp.StatusCode)
|
||||||
|
}
|
||||||
1
go/tempCodeRunnerFile.go
Normal file
1
go/tempCodeRunnerFile.go
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
"os"
|
||||||
Loading…
Reference in a new issue