github.com/keysonZZZ/kmg@v0.0.0-20151121023212-05317bfd7d39/kmgRpc/tplTestPackage/generated.go (about)

     1  package tplTestPackage
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/bronze1man/kmg/kmgCrypto"
     7  
     8  	"github.com/bronze1man/kmg/kmgLog"
     9  
    10  	"github.com/bronze1man/kmg/kmgNet/kmgHttp"
    11  
    12  	"net/http"
    13  
    14  	"bytes"
    15  
    16  	"encoding/json"
    17  
    18  	"errors"
    19  )
    20  
    21  type Client_Demo struct {
    22  	RemoteUrl string // http://kmg.org:1234/
    23  }
    24  
    25  var kmgRpc_Demo_encryptKey = &[32]byte{1, 2}
    26  
    27  const (
    28  	kmgRpc_Demo_ResponseCodeSuccess byte = 1
    29  	kmgRpc_Demo_ResponseCodeError   byte = 2
    30  )
    31  
    32  //server
    33  func ListenAndServe_Demo(addr string, obj *Demo) (closer func() error) {
    34  	s := &generateServer_Demo{
    35  		obj: obj,
    36  	}
    37  	return kmgHttp.MustGoHttpAsyncListenAndServeWithCloser(addr, s)
    38  }
    39  
    40  func NewServer_Demo(obj *Demo) http.Handler {
    41  	return &generateServer_Demo{
    42  		obj: obj,
    43  	}
    44  }
    45  
    46  func NewClient_Demo(RemoteUrl string) *Client_Demo {
    47  	return &Client_Demo{RemoteUrl: RemoteUrl}
    48  }
    49  
    50  type generateServer_Demo struct {
    51  	obj *Demo
    52  }
    53  
    54  // http-json-api v1
    55  // 1.数据传输使用psk加密,明文不泄漏信息
    56  // 2.使用json序列化信息
    57  // 3.只有部分api
    58  func (s *generateServer_Demo) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    59  	b1, err := kmgHttp.RequestReadAllBody(req)
    60  	if err != nil {
    61  		http.Error(w, "error 1", 400)
    62  		kmgLog.Log("InfoServerError", err.Error(), kmgHttp.NewLogStruct(req))
    63  		return
    64  	}
    65  
    66  	//解密
    67  	b1, err = kmgCrypto.CompressAndEncryptBytesDecode(kmgRpc_Demo_encryptKey, b1)
    68  	if err != nil {
    69  		http.Error(w, "error 2", 400)
    70  		kmgLog.Log("InfoServerError", err.Error(), kmgHttp.NewLogStruct(req))
    71  		return
    72  	}
    73  	outBuf, err := s.handleApiV1(b1)
    74  	if err != nil {
    75  		kmgLog.Log("InfoServerError", err.Error(), kmgHttp.NewLogStruct(req))
    76  		outBuf = append([]byte{kmgRpc_Demo_ResponseCodeError}, err.Error()...)
    77  	} else {
    78  		outBuf = append([]byte{kmgRpc_Demo_ResponseCodeSuccess}, outBuf...)
    79  	}
    80  	//加密
    81  	outBuf = kmgCrypto.CompressAndEncryptBytesEncode(kmgRpc_Demo_encryptKey, outBuf)
    82  	w.WriteHeader(200)
    83  	w.Header().Set("Content-type", "image/jpeg")
    84  	w.Write(outBuf)
    85  }
    86  
    87  func (c *Client_Demo) sendRequest(apiName string, inData interface{}, outData interface{}) (err error) {
    88  	inDataByte, err := json.Marshal(inData)
    89  	if err != nil {
    90  		return
    91  	}
    92  	if len(apiName) > 255 {
    93  		return errors.New("len(apiName)>255")
    94  	}
    95  	inByte := []byte{byte(len(apiName))}
    96  	inByte = append(inByte, []byte(apiName)...)
    97  	inByte = append(inByte, inDataByte...)
    98  	inByte = kmgCrypto.CompressAndEncryptBytesEncode(kmgRpc_Demo_encryptKey, inByte)
    99  
   100  	resp, err := http.Post(c.RemoteUrl, "image/jpeg", bytes.NewBuffer(inByte))
   101  	if err != nil {
   102  		return
   103  	}
   104  	outByte, err := kmgHttp.ResponseReadAllBody(resp)
   105  	if err != nil {
   106  		return
   107  	}
   108  	outByte, err = kmgCrypto.CompressAndEncryptBytesDecode(kmgRpc_Demo_encryptKey, outByte)
   109  	if err != nil {
   110  		return
   111  	}
   112  	if len(outByte) == 0 {
   113  		return errors.New("len(outByte)==0")
   114  	}
   115  	switch outByte[0] {
   116  	case kmgRpc_Demo_ResponseCodeError:
   117  		return errors.New(string(outByte[1:]))
   118  	case kmgRpc_Demo_ResponseCodeSuccess:
   119  		return json.Unmarshal(outByte[1:], outData)
   120  	default:
   121  		return fmt.Errorf("httpjsonApi protocol error 1 %d", outByte[0])
   122  	}
   123  }
   124  
   125  func (s *generateServer_Demo) handleApiV1(inBuf []byte) (outBuf []byte, err error) {
   126  	//从此处开始协议正确了,换一种返回方式
   127  	// 1 byte api name len apiNameLen
   128  	// apiNameLen byte api name
   129  	// xx byte json encode of request as struct.
   130  	if len(inBuf) < 2 {
   131  		return nil, fmt.Errorf("len(b1)<2")
   132  	}
   133  	nameLength := inBuf[0]
   134  	if len(inBuf) < int(nameLength)+1 {
   135  		return nil, fmt.Errorf("len(b1)<nameLength+1")
   136  	}
   137  	name := string(inBuf[1 : int(nameLength)+1])
   138  	b2 := inBuf[nameLength+1:]
   139  
   140  	switch name {
   141  
   142  	case "PostScoreInt":
   143  
   144  		var Info string
   145  
   146  		var Err error
   147  		reqData := &struct {
   148  			LbId string
   149  
   150  			Score int
   151  		}{}
   152  		Err = json.Unmarshal(b2, reqData)
   153  		if Err != nil {
   154  			return nil, Err
   155  		}
   156  
   157  		Info, Err = s.obj.PostScoreInt(reqData.LbId, reqData.Score)
   158  		if Err != nil {
   159  			return nil, Err
   160  		}
   161  
   162  		return json.Marshal(struct {
   163  			Info string
   164  		}{
   165  
   166  			Info: Info,
   167  		})
   168  
   169  	}
   170  	return nil, fmt.Errorf("api %s not found", name)
   171  }
   172  
   173  func (c *Client_Demo) PostScoreInt(LbId string, Score int) (Info string, Err error) {
   174  	reqData := &struct {
   175  		LbId string
   176  
   177  		Score int
   178  	}{
   179  
   180  		LbId: LbId,
   181  
   182  		Score: Score,
   183  	}
   184  
   185  	respData := &struct {
   186  		Info string
   187  	}{}
   188  	Err = c.sendRequest("PostScoreInt", reqData, &respData)
   189  	return respData.Info, Err
   190  
   191  }