[링크 : http://golang.site/go/article/103-HTTP-POST-호출]
net/http 패키지에 Get() Post() 명령등을 사용하면 간단하게 보낼수 있는 듯.
resp, err := http.Get("http://example.com/")
...
resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
...
resp, err := http.PostForm("http://example.com/form",
url.Values{"key": {"Value"}, "id": {"123"}})
[링크 : https://pkg.go.dev/net/http]
Put() Delete()는 http.NewRequest()를 이용하여 http.MethodPut / http.MethodDelete 타입으로 만들어 주면
기본 모듈로도 충분히 구현 가능한 것 같다.
func put() { fmt.Println("3. Performing Http Put...") todo := Todo{1, 2, "lorem ipsum dolor sit amet", true} jsonReq, err := json.Marshal(todo) req, err := http.NewRequest(http.MethodPut, "https://jsonplaceholder.typicode.com/todos/1", bytes.NewBuffer(jsonReq)) req.Header.Set("Content-Type", "application/json; charset=utf-8") client := &http.Client{} resp, err := client.Do(req) if err != nil { log.Fatalln(err) } defer resp.Body.Close() bodyBytes, _ := ioutil.ReadAll(resp.Body) // Convert response body to string bodyString := string(bodyBytes) fmt.Println(bodyString) // Convert response body to Todo struct var todoStruct Todo json.Unmarshal(bodyBytes, &todoStruct) fmt.Printf("API Response as struct:\n%+v\n", todoStruct) } func delete() { fmt.Println("4. Performing Http Delete...") todo := Todo{1, 2, "lorem ipsum dolor sit amet", true} jsonReq, err := json.Marshal(todo) req, err := http.NewRequest(http.MethodDelete, "https://jsonplaceholder.typicode.com/todos/1", bytes.NewBuffer(jsonReq)) client := &http.Client{} resp, err := client.Do(req) if err != nil { log.Fatalln(err) } defer resp.Body.Close() bodyBytes, _ := ioutil.ReadAll(resp.Body) // Convert response body to string bodyString := string(bodyBytes) fmt.Println(bodyString) } |
'Programming > golang' 카테고리의 다른 글
golang 함수 인자에 함수 넣기 (0) | 2022.09.27 |
---|---|
golang package main (0) | 2022.09.23 |
golang 'go doc' (0) | 2022.09.15 |
golang main arg, getopt (0) | 2022.09.15 |
golang json (0) | 2022.09.15 |