Exemplo n.º 1
0
// http-json-api v1
// 1.数据传输使用psk加密,明文不泄漏信息
// 2.使用json序列化信息
// 3.只有部分api
func (s *generateServer_ServiceRpc) 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
	}
	if s.psk != nil {
		//解密
		b1, err = kmgCrypto.CompressAndEncryptBytesDecodeV2(s.psk, b1)
		if err != nil {
			http.Error(w, "error 2", 400)
			kmgLog.Log("InfoServerError", err.Error(), kmgHttp.NewLogStruct(req))
			return
		}
	}
	outBuf, err := s.handleApiV1(b1, w, req)
	if err != nil {
		kmgLog.Log("InfoServerError", err.Error(), kmgHttp.NewLogStruct(req))
		outBuf = append([]byte{1}, err.Error()...) // error
	} else {
		outBuf = append([]byte{2}, outBuf...) // success
	}
	if s.psk != nil {
		//加密
		outBuf = kmgCrypto.CompressAndEncryptBytesEncodeV2(s.psk, outBuf)
	}
	w.WriteHeader(200)
	w.Header().Set("Content-type", "image/jpeg")
	w.Write(outBuf)
}
Exemplo n.º 2
0
func AddCommandList() {
	kmgConsole.AddAction(kmgConsole.Command{
		Name:   "FileHttpServer",
		Runner: runFileHttpServer,
	})
	kmgConsole.AddCommandWithName("HttpGet", func() {
		requestUrl := ""
		key := ""
		flag.StringVar(&requestUrl, "url", "", "")
		flag.StringVar(&key, "key", "", "crypto key use to decrypt respond")
		flag.Parse()
		if requestUrl == "" {
			kmgConsole.ExitOnErr(errors.New("Usage: kmg HttpGet -url http://xxx"))
		}
		b := MustUrlGetContent(requestUrl)
		var err error
		if key != "" {
			b, err = kmgCrypto.CompressAndEncryptBytesDecodeV2(kmgCrypto.Get32PskFromString(key), b)
			if err != nil {
				panic(err)
			}
		}
		fmt.Print(string(b))
	})
}
Exemplo n.º 3
0
func (c *Client_ServiceRpc) 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...)
	if c.Psk != nil {
		inByte = kmgCrypto.CompressAndEncryptBytesEncodeV2(c.Psk, 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
	}
	if c.Psk != nil {
		outByte, err = kmgCrypto.CompressAndEncryptBytesDecodeV2(c.Psk, outByte)
		if err != nil {
			return
		}
	}
	if len(outByte) == 0 {
		return errors.New("len(outByte)==0")
	}
	switch outByte[0] {
	case 1: //error
		return errors.New(string(outByte[1:]))
	case 2: //success
		return json.Unmarshal(outByte[1:], outData)
	default:
		return fmt.Errorf("httpjsonApi protocol error 1 %d", outByte[0])
	}
}