Example #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)
}
Example #2
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])
	}
}
Example #3
0
func runFileHttpServer() {
	listenAddr := ""
	path := ""
	key := ""
	flag.StringVar(&listenAddr, "l", ":80", "listen address")
	flag.StringVar(&path, "path", "", "root path of the file server")
	flag.StringVar(&key, "key", "", "crypto key use to encrypt all request of this server")
	flag.Parse()
	var err error
	if path == "" {
		path, err = os.Getwd()
		if err != nil {
			fmt.Printf("os.Getwd() fail %s", err)
			return
		}
	} else {
		kmgErr.PanicIfError(os.Chdir(path))
	}
	if key == "" {
		http.Handle("/", http.FileServer(http.Dir(path)))
	}
	if key != "" {
		http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
			realPath := filepath.Join(path, r.URL.Path)
			if !kmgFile.MustFileExist(realPath) {
				w.Write([]byte("File Not Exist"))
				return
			}
			if !kmgStrings.IsInSlice(cacheFilePathSlice, realPath) {
				cacheFilePathSlice = append(cacheFilePathSlice, realPath)
			}
			updateCache := func() {
				cacheFilePathEncryptMap[realPath] = kmgCrypto.CompressAndEncryptBytesEncodeV2(
					kmgCrypto.Get32PskFromString(key),
					kmgFile.MustReadFile(realPath),
				)
			}
			checkCache := func() {
				lock.Lock()
				defer lock.Unlock()
				kmgCache.MustMd5FileChangeCache(realPath, []string{realPath}, func() {
					updateCache()
				})
			}
			checkCache()
			//进程重启后,内存中的缓存掉了,但是文件系统的缓存还在
			_, exist := cacheFilePathEncryptMap[realPath]
			if !exist {
				updateCache()
			}
			w.Write(cacheFilePathEncryptMap[realPath])
		})
	}
	fmt.Println("start server at", listenAddr)
	err = http.ListenAndServe(listenAddr, nil)
	if err != nil {
		fmt.Printf("http.ListenAndServe() fail %s", err)
		return
	}
	return
}