Пример #1
0
// http-json-api v1
// 1.数据传输使用psk加密,明文不泄漏信息
// 2.使用json序列化信息
// 3.只有部分api
func (s *generateServer_Demo) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	b1, err := kmgHttp.RequestReadAllBody(req)
	if err != nil {
		http.Error(w, "error 1", 400)
		kmgLog.Log("InfoServerError", err.Error(), kmgHttp.NewLogStruct(req))
		return
	}

	//解密
	b1, err = kmgCrypto.CompressAndEncryptBytesDecode(kmgRpc_Demo_encryptKey, b1)
	if err != nil {
		http.Error(w, "error 2", 400)
		kmgLog.Log("InfoServerError", err.Error(), kmgHttp.NewLogStruct(req))
		return
	}
	outBuf, err := s.handleApiV1(b1)
	if err != nil {
		kmgLog.Log("InfoServerError", err.Error(), kmgHttp.NewLogStruct(req))
		outBuf = append([]byte{kmgRpc_Demo_ResponseCodeError}, err.Error()...)
	} else {
		outBuf = append([]byte{kmgRpc_Demo_ResponseCodeSuccess}, outBuf...)
	}
	//加密
	outBuf = kmgCrypto.CompressAndEncryptBytesEncode(kmgRpc_Demo_encryptKey, outBuf)
	w.WriteHeader(200)
	w.Header().Set("Content-type", "image/jpeg")
	w.Write(outBuf)
}
Пример #2
0
func (c *Client_Demo) sendRequest(apiName string, inData interface{}, outData interface{}) (err error) {
	inDataByte, err := json.Marshal(inData)
	if err != nil {
		return
	}
	if len(apiName) > 255 {
		return errors.New("len(apiName)>255")
	}
	inByte := []byte{byte(len(apiName))}
	inByte = append(inByte, []byte(apiName)...)
	inByte = append(inByte, inDataByte...)
	inByte = kmgCrypto.CompressAndEncryptBytesEncode(kmgRpc_Demo_encryptKey, inByte)

	resp, err := http.Post(c.RemoteUrl, "image/jpeg", bytes.NewBuffer(inByte))
	if err != nil {
		return
	}
	outByte, err := kmgHttp.ResponseReadAllBody(resp)
	if err != nil {
		return
	}
	outByte, err = kmgCrypto.CompressAndEncryptBytesDecode(kmgRpc_Demo_encryptKey, outByte)
	if err != nil {
		return
	}
	if len(outByte) == 0 {
		return errors.New("len(outByte)==0")
	}
	switch outByte[0] {
	case kmgRpc_Demo_ResponseCodeError:
		return errors.New(string(outByte[1:]))
	case kmgRpc_Demo_ResponseCodeSuccess:
		return json.Unmarshal(outByte[1:], outData)
	default:
		return fmt.Errorf("httpjsonApi protocol error 1 %d", outByte[0])
	}
}