LuKaicheng 6 年之前
父節點
當前提交
5a7ff65032
共有 8 個文件被更改,包括 155 次插入29 次删除
  1. 9 0
      example/cuser/main.go
  2. 4 12
      example/cuser/service/decode.go
  3. 7 16
      example/cuser/service/router.go
  4. 1 1
      example/gateway/user.go
  5. 43 0
      example/tcpserver/main.go
  6. 1 0
      http/client.go
  7. 24 0
      sys/limit.go
  8. 66 0
      tcp/server.go

+ 9 - 0
example/cuser/main.go

@@ -3,6 +3,7 @@ package main
 import (
 	"flag"
 	"fmt"
+	"io/ioutil"
 	"net/http"
 	"os"
 	"time"
@@ -32,6 +33,14 @@ func main() {
 		khttp.WriteJSON(w, toolkit.RowReplyData(ver))
 	})
 
+	khttp.AddPostHandle(router, "/upload", func(w http.ResponseWriter, r *http.Request) {
+		defer r.Body.Close()
+		body, _ := ioutil.ReadAll(r.Body)
+
+		fmt.Println(string(body))
+		khttp.WriteJSON(w, toolkit.OkReplyData())
+	})
+
 	dns := fmt.Sprintf(
 		"root:Lsar-5211@tcp(127.0.0.1:3306)/community_user?charset=utf8mb4")
 

+ 4 - 12
example/cuser/service/decode.go

@@ -9,9 +9,7 @@ import (
 )
 
 // DecodeGetUserProfileRequest 用户基本信息请求处理
-func DecodeGetUserProfileRequest(
-	_ context.Context,
-	r *http.Request) (interface{}, error) {
+func DecodeGetUserProfileRequest(_ context.Context, r *http.Request) (interface{}, error) {
 	var request define.FormID
 
 	if err := binding.Bind(r, &request); err != nil {
@@ -21,9 +19,7 @@ func DecodeGetUserProfileRequest(
 }
 
 // DecodeGetUserListRequest 用户列表信息请求处理
-func DecodeGetUserListRequest(
-	_ context.Context,
-	r *http.Request) (interface{}, error) {
+func DecodeGetUserListRequest(_ context.Context, r *http.Request) (interface{}, error) {
 	var request define.FormUser
 
 	if err := binding.Bind(r, &request); err != nil {
@@ -33,9 +29,7 @@ func DecodeGetUserListRequest(
 }
 
 // DecodePostUserSignInRequest 用户登录
-func DecodePostUserSignInRequest(
-	ctx context.Context,
-	r *http.Request) (interface{}, error) {
+func DecodePostUserSignInRequest(ctx context.Context, r *http.Request) (interface{}, error) {
 	var request define.FormUserSignIn
 
 	if err := binding.Bind(r, &request); err != nil {
@@ -45,9 +39,7 @@ func DecodePostUserSignInRequest(
 }
 
 // DecodePostUserChangePwdRequest 用户修改密码
-func DecodePostUserChangePwdRequest(
-	ctx context.Context,
-	r *http.Request) (interface{}, error) {
+func DecodePostUserChangePwdRequest(ctx context.Context, r *http.Request) (interface{}, error) {
 	var request define.FormUserChangePwd
 
 	if err := binding.Bind(r, &request); err != nil {

+ 7 - 16
example/cuser/service/router.go

@@ -2,7 +2,6 @@ package service
 
 import (
 	"context"
-	"csacred/define/router"
 
 	"git.chuangxin1.com/csacred/toolkit/example/cuser/define"
 	"git.chuangxin1.com/csacred/toolkit/http"
@@ -11,10 +10,7 @@ import (
 )
 
 // API gateway factory
-func factory(
-	ctx context.Context,
-	instancer *consulsd.Instancer,
-	logger log.Logger) Endpoints {
+func factory(ctx context.Context, instancer *consulsd.Instancer, logger log.Logger) Endpoints {
 	e := Endpoints{}
 
 	var lb http.LoadBalancer
@@ -42,18 +38,16 @@ func factory(
 func endpointHanders(endpoints Endpoints) []http.EndpointRouter {
 	var handers []http.EndpointRouter
 
-	handers = append(handers, http.GetEndpointRouter(router.RouteUserGetProfile, DecodeGetUserProfileRequest, http.WriteCtxJSON, endpoints.UserProfileEndpoint))
-	handers = append(handers, http.GetEndpointRouter(router.RouteUserGetList, DecodeGetUserListRequest, http.WriteCtxJSON, endpoints.UserListEndpoint))
-	handers = append(handers, http.PostEndpointRouter(router.RouteUserPostSignIn, DecodePostUserSignInRequest, http.WriteCtxJSON, endpoints.UserSignInEndpoint))
-	handers = append(handers, http.PostEndpointRouter(router.RouteUserPostChangePwd, DecodePostUserChangePwdRequest, http.WriteCtxJSON, endpoints.UserChangePwdEndpoint))
+	handers = append(handers, http.GetEndpointRouter(define.RouteUserGetProfile, DecodeGetUserProfileRequest, http.WriteCtxJSON, endpoints.UserProfileEndpoint))
+	handers = append(handers, http.GetEndpointRouter(define.RouteUserGetList, DecodeGetUserListRequest, http.WriteCtxJSON, endpoints.UserListEndpoint))
+	handers = append(handers, http.PostEndpointRouter(define.RouteUserPostSignIn, DecodePostUserSignInRequest, http.WriteCtxJSON, endpoints.UserSignInEndpoint))
+	handers = append(handers, http.PostEndpointRouter(define.RouteUserPostChangePwd, DecodePostUserChangePwdRequest, http.WriteCtxJSON, endpoints.UserChangePwdEndpoint))
 
 	return handers
 }
 
 // GenServiceHandler service handler
-func GenServiceHandler(
-	s UserServicer,
-	logger log.Logger) []http.RouterHandler {
+func GenServiceHandler(s UserServicer, logger log.Logger) []http.RouterHandler {
 	var handers []http.RouterHandler
 
 	e := GenServerEndpoints(s)
@@ -65,10 +59,7 @@ func GenServiceHandler(
 }
 
 // GenGatewayHandlers gateway handlers
-func GenGatewayHandlers(
-	ctx context.Context,
-	instancer *consulsd.Instancer,
-	logger log.Logger) []http.RouterHandler {
+func GenGatewayHandlers(ctx context.Context, instancer *consulsd.Instancer, logger log.Logger) []http.RouterHandler {
 	var handers []http.RouterHandler
 
 	e := factory(ctx, instancer, logger)

+ 1 - 1
example/gateway/user.go

@@ -35,7 +35,7 @@ func genUserHandlers(
 	}
 
 	handers := users.GenGatewayHandlers(ctx, instancer, logger)
-	prefix := "/" + name + "/" + ver
+	prefix := "/api/" + name + "/" + ver
 	//ctx = context.WithValue(ctx, contextKeyPrefix, prefix)
 	for i := range handers {
 		fmt.Println(handers[i].Method, prefix+handers[i].Router)

+ 43 - 0
example/tcpserver/main.go

@@ -0,0 +1,43 @@
+package main
+
+import (
+	"fmt"
+	"io"
+	"net"
+	"time"
+
+	"git.chuangxin1.com/csacred/toolkit/tcp"
+)
+
+func main() {
+	tcp.NewTCPServer(":2020", func(conn *net.TCPConn) {
+		defer conn.Close()
+
+		conn.SetNoDelay(true)
+		//conn.SetKeepAlive(keepalive)
+		//bufr := bufio.NewReader(conn)
+		var buf = make([]byte, 4096)
+		for {
+			conn.SetReadDeadline(time.Now().Add(time.Second * 10))
+
+			//n, err := bufr.Read(buf)
+			n, err := conn.Read(buf)
+			if err != nil {
+				if err == io.EOF {
+					fmt.Println("EOF")
+				} else if operr, ok := err.(*net.OpError); ok {
+					fmt.Println("net.OpError")
+					if operr.Timeout() {
+						fmt.Println("I/O timeout: ", conn.RemoteAddr().String(), time.Now().Format("2006-01-02 15:04:05"))
+						continue
+					}
+				}
+				fmt.Println("err:", err)
+				break
+			}
+			fmt.Printf("Read %d bytes\n", n)
+			conn.Write(buf[:n])
+		}
+		println("End ", conn.RemoteAddr().String())
+	})
+}

+ 1 - 0
http/client.go

@@ -0,0 +1 @@
+package http

+ 24 - 0
sys/limit.go

@@ -0,0 +1,24 @@
+package sys
+
+import (
+	"syscall"
+)
+
+// SetLimit set NOFILE
+func SetLimit(uint64 max) error {
+	var rlimit syscall.Rlimit
+
+	err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit)
+	if err != nil {
+		return err
+	}
+
+	rlimit.Cur = max
+	rlimit.Max = max
+	err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rlimit)
+	if err != nil {
+		return err
+	}
+
+	return nil
+}

+ 66 - 0
tcp/server.go

@@ -0,0 +1,66 @@
+package tcp
+
+import (
+	"fmt"
+	"log"
+	"net"
+	"os"
+	"os/signal"
+	"syscall"
+)
+
+// NewTCPServer make TCP server
+func NewTCPServer(addr string, cb func(*net.TCPConn)) {
+	var (
+		//buffer bytes.Buffer
+		logger = log.New(os.Stdout, "INFO: ", log.Lshortfile)
+	)
+	// Interrupt handler.
+	errc := make(chan error)
+	go func() {
+		c := make(chan os.Signal)
+		signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
+		errc <- fmt.Errorf("%s", <-c)
+	}()
+
+	tcpaddr, err := net.ResolveTCPAddr("tcp", ":2020")
+	if err != nil {
+		logger.Fatalf("listen error: %v", err)
+		return
+	}
+
+	listen, err := net.ListenTCP("tcp", tcpaddr)
+	if err != nil {
+		logger.Fatalf("listen error: %v", err)
+		return
+	}
+	defer listen.Close()
+
+	go func() {
+		logger.Println("TCP Listen", addr)
+		//log..Log("Protocol", "HTTP", "addr", addr)
+		//errc <- server.ListenAndServe()
+		for {
+			conn, err := listen.Accept()
+			if err != nil {
+				errc <- err
+				log.Fatalf("accept error: %v", err)
+				break
+			}
+
+			tcpConn, ok := conn.(*net.TCPConn)
+			if !ok {
+				//error handle
+				conn.Close()
+				continue
+			}
+
+			go cb(tcpConn)
+		}
+		logger.Println("Exit server", "Quit")
+	}()
+
+	// Run!
+	//logger.Log("Exit", <-errc)
+	logger.Println("Exit", <-errc)
+}