안녕하세요. 오늘은 golang에서 post를 사용하는 방법에 대해서 많은 분들이 어려워하실 것 같습니다.
그래서 제가 간단한 사용을 통해서 실제로 적용 가능한 코드를 알려드리겠습니다. 저도 해당 코드를 통해서 실제 서비스에서 사용하고 있습니다.
제가 사용한 방식은 요즘 많이 사용하는 Json 방식으로 보내는 방법입니다.
제가 사용하는 방법에서 비효율적인 부분이 존재하거나 추가되었으면 하는 부분이 있으면 댓글로 남겨놔 주세요~!
제가 실제 visual studio code에서 가지고 온 코드를 코드 블록에 추가했지만, 정상적으로 들여 쓰기가 안 맞는 것처럼 보일 수 있으니 이해 부탁드립니다.
import (
"bytes"
"io/ioutil"
"net/http"
"encoding/json"
)
func main() {
//json 객체를 위해서는 먼저 본인의 객체를 구조체로 정의해서 사용해야합니다.
pbytes, _ := json.Marshal("json 객체")
buff := bytes.NewBuffer(pbytes)
//request 객체 생성
req, err := http.NewRequest("POST","localhost:9200", buff)
if err != nil {
panic(err)
}
//Content-Type 헤더 추가
req.Header.Add("Content-Type","application/json")
//client 객체에서 Request 실행
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
//request에 대한 응답
respBody, err := ioutil.ReadAll(resp.Body)
if err == nil {
str := string(respBody)
}
}