go client get/post

func httpPost(pBody string) {
	resp, err := http.Post("http://101.132.137.62:80/otv/lizhiyun/live/rtmp_stop",
		"application/x-www-form-urlencoded",
		strings.NewReader(pBody))
	if err != nil {
		log.Fatal("httpPost  error:" + err.Error())
		return
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// handle error
		log.Fatal("no resp  error:" + err.Error())
		return
	}
	fmt.Println(string(body))
	log.Debug("ugslb resp with body:%s", string(body))
}

		//构造post请求
		var postBody string
		postBody = "rtmp_url=" + st.RtmpUrl + ";roomID=" + st.RoomID + "\r\n"
		log.Debug("postBody:%s", postBody)
		httpPost(postBody)

func httpPost(pUrl string, pBody string) {
	resp, err := http.Post(pUrl,
		"application/x-www-form-urlencoded",
		strings.NewReader(pBody))
	if err != nil {
		log.Fatal("httpPost  error:" + err.Error())
		return
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// handle error
		log.Fatal("no resp  error:" + err.Error())
		return
	}
	fmt.Println(string(body))
	log.Debug("ugslb resp with body:%s", string(body))
}
//使用
type changeStateMessage struct {
 Id        string `json:"id"`
 Livestate string `json:"livestate"`
}
func main() {
 //notify 3rd change state
 csOutM := &changeStateMessage{
  "1234",
  "1",
 }
 bo, errMar := json.Marshal(csOutM)
 if errMar != nil {
  log.Fatal("json encode message failed")
 }
 boStr := string(bo)
 fmt.Println("push boStr:", boStr)
 httpPost("http://47.2.9.5/HaikanH5/LiveeventWS/ChangeState", boStr)
}

func httpGet(head string) {
	u, _ := url.Parse(head)
	q := u.Query()
	u.RawQuery = q.Encode()
	res, err := http.Get(u.String())
	if err != nil {
		log.Fatal("http head get with error:" + err.Error())
		return
	}
	result, err := ioutil.ReadAll(res.Body)
	res.Body.Close()
	if err != nil {
		log.Fatal("http head resp with error:" + err.Error())
		return
	}
	log.Debug("ugslb resp with body:%s", string(result))
}

		getUrl := "http://localhost:80/otv/lizhiyun/live/rtmp_start?" + "rtmp_url=" + st.RtmpUrl + "&roomID=" + st.RoomID
		log.Debug("push getUrl:%s", getUrl)
		httpGet(getUrl)、
项目实践:
func httpPostWithAuth(pUrl string, pBody []byte) {
	//生成client 参数为默认
	client := &http.Client{}

	//提交请求
	request, err := http.NewRequest("POST", pUrl, bytes.NewReader(pBody))

	if err != nil {
		panic(err)
	}

	request.Proto = "HTTP/1.1"
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	request.Header.Add("Authorization", "GqzR7yqCTZkFW6lF4aB5hWUkSUk")

	log4plus.Debug("6666666before post")

	//处理返回结果
	response, err := client.Do(request)

	if err == nil {
		body, err := ioutil.ReadAll(response.Body)
		if err != nil {
			// handle error
			log4plus.Error("no resp  error:" + err.Error())
			return
		}
		//返回的状态码
		status := response.StatusCode

		log4plus.Debug("resp with body:%s, httpCode:%v", string(body), status)

	} else {
		log4plus.Error("6666666httpPost  resp with error:" + err.Error())
	}

}
			var picPaths tsFrameBody
			picPaths.Urls = append(picPaths.Urls, accessPath)

			//notify monitor when the timeout happened

			b, err := json.Marshal(picPaths)
			if err != nil {
				log4plus.Error("json encode message failed, %s", string(b))
			} else {
				log4plus.Debug("post content:%s", string(b))
				alarmPtr.SendMessage2Url("http://ip:port/yfy/spy", b)
			}
func (alarmPtr *Alarm) SendMessage2Url(url string, body []byte) bool {
	httpPostWithAuth(url, body)
	return true
}


post 文件:

package main

import (
    "bytes"
    "fmt"
    "io"
    "mime/multipart"
    "net/http"
    "os"
)

func postFile(filename string, target_url string) (*http.Response, error) {
    body_buf := bytes.NewBufferString("")
    body_writer := multipart.NewWriter(body_buf)

    // use the body_writer to write the Part headers to the buffer
    _, err := body_writer.CreateFormFile("userfile", filename)
    if err != nil {
        fmt.Println("error writing to buffer")
        return nil, err
    }

    // the file data will be the second part of the body
    fh, err := os.Open(filename)
    if err != nil {
        fmt.Println("error opening file")
        return nil, err
    }
    // need to know the boundary to properly close the part myself.
    boundary := body_writer.Boundary()
    //close_string := fmt.Sprintf("\r\n--%s--\r\n", boundary)
    close_buf := bytes.NewBufferString(fmt.Sprintf("\r\n--%s--\r\n", boundary))

    // use multi-reader to defer the reading of the file data until
    // writing to the socket buffer.
    request_reader := io.MultiReader(body_buf, fh, close_buf)
    fi, err := fh.Stat()
    if err != nil {
        fmt.Printf("Error Stating file: %s", filename)
        return nil, err
    }
    req, err := http.NewRequest("POST", target_url, request_reader)
    if err != nil {
        return nil, err
    }

    // Set headers for multipart, and Content Length
    req.Header.Add("Content-Type", "multipart/form-data; boundary="+boundary)
    req.ContentLength = fi.Size() + int64(body_buf.Len()) + int64(close_buf.Len())

    return http.DefaultClient.Do(req)
}

// sample usage
func main() {
    target_url := "http://localhost:8086/upload"
    filename := "/Users/wei/Downloads/21dian_1.9_10"
    postFile(filename, target_url)
}






  

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值