Intel® Collaboration Suite for WebRTC
Community support and discussions on the Intel® Collaboration Suite for WebRTC (Intel® CS for WebRTC).
Announcements
Intel Customer Support will be observing the Martin Luther King holiday on Monday, Jan. 17, and will return on Tues. Jan. 18.
For the latest information on Intel’s response to the Log4j/Log4Shell vulnerability, please see Intel-SA-00646
1135 Discussions

新手入门:golang 实现请求接口demo

libojacky
Beginner
496 Views
此实现只是demo,可自行优化

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"github.com/gojektech/heimdall"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
	"github.com/labstack/echo"
	"encoding/json"
)

//创建房间
func createRoom(url,room string) string{
	requestBody := ""
	result := send(url,"post",requestBody)
	return result
}

//url:接口地址
//method: get post ...
//requestBody 请求主体
func send(url, method, requestBody string) string {
	//key
	key := ""
	//serviceid
	serviceid := ""

	//时间戳 到毫秒
	timestamp := utils.ToString(time.Now().UnixNano() / 1e6)
	//随机数
	cnounce := utils.Krand(8, utils.KC_RAND_KIND_NUM)
	//签名需要的参数
	toSign := timestamp + "," + cnounce
	//签名
	signed := calculateSignature(toSign, key)
	//Header 信息
	header := "MAuth realm=http://marte3.dit.upm.es,mauth_signature_method=HMAC_SHA256"
	header = header + ",mauth_serviceid=" + serviceid
	header = header + ",mauth_cnonce=" + cnounce
	header = header + ",mauth_timestamp=" + timestamp
	header = header + ",mauth_signature=" + signed

	timeout := 1000 * time.Millisecond
	httpClient := heimdall.NewHTTPClient(timeout)
	headers := http.Header{}
	headers.Set("Content-Type", "application/json")
	headers.Set("Authorization", header)
	httpClient.SetRetryCount(2)
	httpClient.SetRetrier(heimdall.NewRetrier(heimdall.NewConstantBackoff(10, 5)))

	result := ""
	switch method {

	case "get":
		response, err := httpClient.Get(url, headers)
		if err != nil {
			logs.Logger.Error("===============> get send错误处理:" + err.Error())
		}
		defer response.Body.Close()
		respBody, err := ioutil.ReadAll(response.Body)
		if err != nil {
			logs.Logger.Error("===============> get send ReadAll 错误处理:" + err.Error())
		}
		result = string(respBody)
		break
	case "post":
		response, err := httpClient.Post(url, strings.NewReader(requestBody), headers)
		if err != nil {
			logs.Logger.Error("===============> post send错误处理:" + err.Error())
		}
		defer response.Body.Close()
		respBody, err := ioutil.ReadAll(response.Body)
		if err != nil {
			logs.Logger.Error("===============> post send ReadAll 错误处理:" + err.Error())
		}
		result = string(respBody)
		break
	}
	return result
}

//base64编码
func calculateSignature(toSign, key string) string {
	signed := getHmacCode(toSign, key)
	return base64.StdEncoding.EncodeToString([]byte(signed))
}

//HmacSha265
func getHmacCode(s, key string) string {
	h := hmac.New(sha256.New, []byte(key))
	io.WriteString(h, s)
	return fmt.Sprintf("%x", h.Sum(nil))
}

 

0 Kudos
0 Replies
Reply