Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "encoding/json"
- "fmt"
- "io"
- "log"
- "net"
- "os"
- "strings"
- "github.com/saintfish/chardet"
- "golang.org/x/text/encoding/charmap"
- )
- //R request
- type R []interface{}
- func handleConnection(conn net.Conn) {
- defer conn.Close()
- b := make([]byte, (1024 * 4))
- var typeRequest string
- for {
- readLen, err := conn.Read(b)
- if err == io.EOF {
- return
- }
- if string(b[0:1]) == "j" {
- typeRequest = "json"
- continue
- }
- detector := chardet.NewTextDetector()
- decoding, err := detector.DetectBest(b)
- if (decoding.Charset != "windows-1251" && decoding.Charset != "UTF-8") {
- fmt.Println("error charset, only cp1251 or utf8")
- break
- }
- if err == nil {
- //plain cp1251
- if decoding.Charset == "windows-1251" {
- dec := charmap.Windows1251.NewDecoder()
- newBody := make([]byte, len(b)*2)
- n, _, err := dec.Transform(newBody, b, false)
- if err == nil {
- newBody = newBody[:n]
- fmt.Println(string(newBody))
- }
- break
- }
- //json
- if typeRequest == "json" {
- body := make([]R, 0)
- request := strings.Split(string(b[:readLen]), "\t")
- err := json.Unmarshal([]byte(request[0]), &body)
- fmt.Println(body)
- if err == nil {
- if len(body) >= 1 {
- cmd := body[0][0]
- if cmd == "send2" {
- fmt.Printf("cmd: send2, cmd_req: %v\n", cmd)
- data := body[0][1]
- for _, d := range data.([]interface{}) {
- fmt.Println(d)
- }
- } else if cmd == "send" {
- fmt.Printf("cmd: send, cmd_req: %v\n", cmd)
- for _, data := range body[0][1].([]interface{}) {
- for _, d := range data.([]interface{}) {
- fmt.Println(d)
- }
- }
- }
- }
- }
- break
- } else {
- //plain
- fmt.Println(string(b[:readLen]))
- break
- }
- }
- }
- }
- func main() {
- ln, err := net.Listen("tcp", "bill.ural.ru:3333")
- if err != nil {
- log.Printf("Error starting server: %s", err)
- os.Exit(1)
- }
- for {
- conn, err := ln.Accept()
- if err != nil {
- log.Printf("Could not accept connection: %s", err)
- continue
- }
- go handleConnection(conn)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement