Golang의 http 요청 보내기, GET, POST

2735 단어

1. GET

func Get(url string, params map[string]string, headers map[string]string) (*http.Response, error) {
	//new request
	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		log.Println(err)
		return nil, errors.New("new request is fail ")
	}
	//add params
	q := req.URL.Query()
	if params != nil {
		for key, val := range params {
			q.Add(key, val)
		}
		req.URL.RawQuery = q.Encode()
	}
	//add headers
	if headers != nil {
		for key, val := range headers {
			req.Header.Add(key, val)
		}
	}
	//http client
	client := &http.Client{}
	log.Printf("Go %s URL : %s 
"
,http.MethodGet, req.URL.String()) return client.Do(req) }

2. POST

func Post(url string, body interface{}, params map[string]string, headers map[string]string) (*http.Response, error) {
	//add post body
	var bodyJson []byte
	var req *http.Request
	if body != nil {
		var err error
		bodyJson, err = json.Marshal(body)
		if err != nil {
			log.Println(err)
			return nil, errors.New("http post body to json failed")
		}
	}
	req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(bodyJson))
	if err != nil {
		log.Println(err)
		return nil, errors.New("new request is fail: %v 
"
) } req.Header.Set("Content-type", "application/json") //add params q := req.URL.Query() if params != nil { for key, val := range params { q.Add(key, val) } req.URL.RawQuery = q.Encode() } //add headers if headers != nil { for key, val := range headers { req.Header.Add(key, val) } } //http client client := &http.Client{} log.Printf("Go %s URL : %s
"
, http.MethodPost,req.URL.String()) return client.Do(req) }

3. PUT 참조 POST

좋은 웹페이지 즐겨찾기