feat 不知道改了什么

This commit is contained in:
huangkun 2024-12-24 15:54:37 +08:00
parent 4e392e9746
commit dc9d8b6e94
27 changed files with 327 additions and 311 deletions

View File

@ -3,12 +3,12 @@ package main
import (
"fmt"
"log"
"os"
"net/http"
"net"
"net/http"
"os"
)
func get(resp http.ResponseWriter, req *http.Request){
func get(resp http.ResponseWriter, req *http.Request) {
hostname, err := os.Hostname()
if err != nil {
resp.Write([]byte(fmt.Sprintf("get hostname error:%v", err)))
@ -20,14 +20,14 @@ func get(resp http.ResponseWriter, req *http.Request){
return
}
addrString := ""
for _, addr := range addrs{
for _, addr := range addrs {
addrString += " " + addr.String()
}
resp.Write([]byte(fmt.Sprintf("response from host: %s, ip is:%s", hostname, addrString)))
}
//read the file which path is "/data/test.txt"
func readFile(resp http.ResponseWriter, req *http.Request){
// read the file which path is "/data/test.txt"
func readFile(resp http.ResponseWriter, req *http.Request) {
file, err := os.Open("/data/test.txt")
if err != nil {
resp.Write([]byte(fmt.Sprintf("open /data/test.txt error:%v", err)))
@ -43,8 +43,8 @@ func readFile(resp http.ResponseWriter, req *http.Request){
resp.Write(data[0:n])
}
//write a string to the file
func writeFile(resp http.ResponseWriter, req *http.Request){
// write a string to the file
func writeFile(resp http.ResponseWriter, req *http.Request) {
file, err := os.OpenFile("/data/test.txt", os.O_RDWR|os.O_APPEND, os.ModePerm)
if err != nil {
resp.Write([]byte(fmt.Sprintf("open /data/test.txt error:%v", err)))
@ -60,7 +60,7 @@ func writeFile(resp http.ResponseWriter, req *http.Request){
resp.Write([]byte("write file successed."))
}
func main (){
func main() {
router := http.DefaultServeMux
router.HandleFunc("/", get)
router.HandleFunc("/read", readFile)
@ -70,4 +70,4 @@ func main (){
if err != nil {
log.Fatalln(err)
}
}
}

View File

@ -6,28 +6,27 @@ import (
"github.com/spf13/cobra"
)
func main(){
func main() {
cmd := cobra.Command{
Use: "cobra",
Use: "cobra",
Short: "this is a cobra demo",
Run: func(cmd *cobra.Command, args []string){
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("good! you run a cobra command!")
},
}
var newLine *bool
subCmd := cobra.Command{
Use: "echo",
Use: "echo",
Short: "echo your input",
Run: func(cmd *cobra.Command, args []string){
Run: func(cmd *cobra.Command, args []string) {
for _, arg := range args {
if newLine != nil && *newLine{
if newLine != nil && *newLine {
fmt.Println(arg)
}else{
} else {
fmt.Printf("%s ", arg)
}
}
if newLine == nil || ! *newLine{
if newLine == nil || !*newLine {
fmt.Println()
}
},
@ -36,4 +35,4 @@ func main(){
cmd.AddCommand(&subCmd)
cmd.Execute()
}
}

View File

@ -8,25 +8,40 @@ import (
"time"
)
const (
RedMax = 33
RedMax = 33
BlueMax = 16
)
func randRate(){
rand.Seed(time.Now().UnixNano())
rate := rand.Intn(100) + 1
fmt.Printf("\t (中奖概率%d%%)", rate)
type ball struct{
B int
R []int
Rate int
}
func randBall(max int)int{
rand.Seed(time.Now().UnixNano())
return rand.Intn(max) + 1
func (b ball)display(){
for _, r := range b.R {
fmt.Printf("\033[1;31;40m%d\033[0m \t", r)
}
fmt.Printf("\033[1;34;40m%d\033[0m \t", b.B)
fmt.Printf("\t (中奖概率%d%%)\n", b.Rate)
}
func isIn(list []int, item int )bool{
for _, i := range list{
func randRate() int {
src := rand.NewSource(time.Now().UnixNano())
rd := rand.New(src)
rate := rd.Intn(100) + 1
return rate
}
func randBall(max int) int {
src := rand.NewSource(time.Now().UnixNano())
rd := rand.New(src)
return rd.Intn(max) + 1
}
func isIn(list []int, item int) bool {
for _, i := range list {
if i == item {
return true
}
@ -34,35 +49,46 @@ func isIn(list []int, item int )bool{
return false
}
func randDoubleBall(){
balls := []int{}
for i := 0; i < 6;{
ball := randBall(RedMax)
if isIn(balls, ball) {
func randDoubleBall()ball{
b := ball{}
for i := 0; i < 6; {
r := randBall(RedMax)
if isIn(b.R, r) {
continue
}
i++
balls = append(balls, ball)
b.R = append(b.R, r)
}
sort.Ints(balls)
blueball := randBall(BlueMax)
for _, ball := range balls {
fmt.Printf("\033[1;31;40m%d\033[0m \t", ball)
}
fmt.Printf("\033[1;34;40m%d\033[0m \t", blueball)
randRate()
fmt.Println("")
sort.Ints(b.R)
b.B = randBall(BlueMax)
b.Rate = randRate()
return b
}
func main(){
func main() {
var groups int
flag.IntVar(&groups, "g", 1, "注数")
var zhong bool
flag.IntVar(&groups, "g", 0, "注数")
flag.BoolVar(&zhong, "z", true, "必中")
flag.Parse()
if groups < 0 {
if groups < 1 {
groups = 1
}else{
zhong = false
}
if zhong {
for {
b := randDoubleBall()
if b.Rate == 100 {
b.display()
break
}
}
return
}
fmt.Printf("为您选取了 %d 注随机双色球,祝君中奖!\n", groups)
for i := 0; i < groups; i++ {
randDoubleBall()
b:=randDoubleBall()
b.display()
}
}
}

View File

@ -1,7 +1,5 @@
package font
type Font struct{
type Font struct {
Head Head `json:"head"`
}
}

View File

@ -1,10 +1,10 @@
package font
type Head struct {
Version string `json:"version"`
TableCount uint16 `json:"tableCount"`
Version string `json:"version"`
TableCount uint16 `json:"tableCount"`
Tables []Table `json:"tables"`
SearchRange uint16 `json:"searchRange"`
EntrySelector uint16 `json:"entrySelector"`
RangeShift uint16 `json:"rangeShift"`
SearchRange uint16 `json:"searchRange"`
EntrySelector uint16 `json:"entrySelector"`
RangeShift uint16 `json:"rangeShift"`
}

View File

@ -3,6 +3,6 @@ package font
type Table struct {
Name string `json:"name"`
Sum uint32 `json:"sum"`
Offset uint32 `json:"offset"`
Offset uint32 `json:"offset"`
Length uint32 `json:"length"`
}

View File

@ -86,26 +86,25 @@ type NameTable struct {
Style string `json:"style"`
}
type NameRecord struct{
Platform uint16
type NameRecord struct {
Platform uint16
PlatformSpecific uint16
Language uint16
Name uint16
Language uint16
Name uint16
Length uint16
Offset uint16
}
type LangTagRecord struct {
Length uint16
Offset uint16
}
type LangTagRecord struct{
Length uint16
Offset uint16
}
type NameTableFormat struct{
Format uint16
RecordsCount uint16
StringOffset uint16
NameRecords []NameRecord
LangTagCount uint16 //only ver 1, apple not support
type NameTableFormat struct {
Format uint16
RecordsCount uint16
StringOffset uint16
NameRecords []NameRecord
LangTagCount uint16 //only ver 1, apple not support
LangTagRecords []LangTagRecord //only ver 1, apple not support
}
}

View File

@ -7,7 +7,7 @@ import (
"os"
)
func readInt8(fp *os.File)(int8, error){
func readInt8(fp *os.File) (int8, error) {
buff := make([]byte, 1)
_, err := fp.Read(buff)
if err != nil {
@ -18,7 +18,7 @@ func readInt8(fp *os.File)(int8, error){
return n, binary.Read(reader, binary.LittleEndian, &n)
}
func readInt16(fp *os.File)(int16, error){
func readInt16(fp *os.File) (int16, error) {
buff := make([]byte, 2)
_, err := fp.Read(buff)
if err != nil {
@ -29,7 +29,7 @@ func readInt16(fp *os.File)(int16, error){
return n, binary.Read(reader, binary.LittleEndian, &n)
}
func readInt32(fp *os.File)(int32, error){
func readInt32(fp *os.File) (int32, error) {
buff := make([]byte, 4)
_, err := fp.Read(buff)
if err != nil {
@ -40,7 +40,7 @@ func readInt32(fp *os.File)(int32, error){
return n, binary.Read(reader, binary.LittleEndian, &n)
}
func readInt64(fp *os.File)(int64, error){
func readInt64(fp *os.File) (int64, error) {
buff := make([]byte, 8)
_, err := fp.Read(buff)
if err != nil {
@ -51,7 +51,7 @@ func readInt64(fp *os.File)(int64, error){
return n, binary.Read(reader, binary.LittleEndian, &n)
}
func readUint8(fp *os.File)(uint8, error){
func readUint8(fp *os.File) (uint8, error) {
buff := make([]byte, 1)
_, err := fp.Read(buff)
if err != nil {
@ -60,7 +60,7 @@ func readUint8(fp *os.File)(uint8, error){
return uint8(buff[0]), nil
}
func readUint16(fp *os.File)(uint16, error){
func readUint16(fp *os.File) (uint16, error) {
buff := make([]byte, 2)
_, err := fp.Read(buff)
if err != nil {
@ -69,7 +69,7 @@ func readUint16(fp *os.File)(uint16, error){
return binary.BigEndian.Uint16(buff), nil
}
func readUint32(fp *os.File)(uint32, error){
func readUint32(fp *os.File) (uint32, error) {
buff := make([]byte, 4)
_, err := fp.Read(buff)
if err != nil {
@ -78,7 +78,7 @@ func readUint32(fp *os.File)(uint32, error){
return binary.BigEndian.Uint32(buff), nil
}
func readUint64(fp *os.File)(uint64, error){
func readUint64(fp *os.File) (uint64, error) {
buff := make([]byte, 8)
_, err := fp.Read(buff)
if err != nil {
@ -87,7 +87,7 @@ func readUint64(fp *os.File)(uint64, error){
return binary.BigEndian.Uint64(buff), nil
}
func readString(fp *os.File, len int)(string, error){
func readString(fp *os.File, len int) (string, error) {
buff := make([]byte, len)
_, err := fp.Read(buff)
if err != nil {
@ -96,7 +96,7 @@ func readString(fp *os.File, len int)(string, error){
return string(buff), nil
}
func readBytes(fp *os.File, len int)([]byte, error){
func readBytes(fp *os.File, len int) ([]byte, error) {
buff := make([]byte, len)
_, err := fp.Read(buff)
if err != nil {
@ -105,7 +105,7 @@ func readBytes(fp *os.File, len int)([]byte, error){
return buff, nil
}
func readFontSearchArgs(fp *os.File)([]uint16, error){
func readFontSearchArgs(fp *os.File) ([]uint16, error) {
ret := []uint16{}
arg1, err := readUint16(fp)
if err != nil {
@ -125,17 +125,17 @@ func readFontSearchArgs(fp *os.File)([]uint16, error){
return ret, nil
}
type ftable struct{
Name string
Sum uint32
type ftable struct {
Name string
Sum uint32
Offset uint32
Length uint32
}
func readFontTables(fp *os.File, tables uint16)([]ftable, error){
func readFontTables(fp *os.File, tables uint16) ([]ftable, error) {
ret := []ftable{}
for i := 0; i < int(tables); i++ {
t :=ftable{}
t := ftable{}
name, err := readString(fp, 4)
if err != nil {
return ret, err
@ -161,12 +161,12 @@ func readFontTables(fp *os.File, tables uint16)([]ftable, error){
return ret, nil
}
func readNameTable(fp *os.File, offset uint32, length uint32)([]byte, error){
func readNameTable(fp *os.File, offset uint32, length uint32) ([]byte, error) {
fp.Seek(int64(offset), 0)
return readBytes(fp, int(length))
}
func readFont(file string)error{
func readFont(file string) error {
fp, err := os.OpenFile(file, os.O_RDONLY, os.ModePerm)
if err != nil {
return err
@ -209,9 +209,9 @@ func readFont(file string)error{
return nil
}
func main(){
func main() {
err := readFont("文鼎中黑.ttf")
if err != nil {
panic(err)
}
}
}

View File

@ -6,14 +6,13 @@ import (
"github.com/gin-gonic/gin"
)
func get(c *gin.Context){
func get(c *gin.Context) {
//c.ClientIP()
log.Println()
}
func main(){
func main() {
engine := gin.Default()
engine.GET("/", get)
engine.Run("0.0.0.0:10000")
}
}

View File

@ -7,9 +7,7 @@ import (
"github.com/spf13/cobra"
)
func show(file string)error{
func show(file string) error {
mp3File, err := id3v2.Open(file, id3v2.Options{Parse: true})
if err != nil {
return err
@ -24,10 +22,10 @@ func show(file string)error{
return nil
}
func set()*cobra.Command{
func set() *cobra.Command {
var artist, title, genre, year, version, album, file string
cmd := &cobra.Command{
Use: "set",
Use: "set",
Short: "set [options] set mp3 file info",
Run: func(cmd *cobra.Command, args []string) {
mp3File, err := id3v2.Open(file, id3v2.Options{Parse: true})
@ -41,7 +39,7 @@ func set()*cobra.Command{
if title != "" {
mp3File.SetTitle(title)
}
if album != ""{
if album != "" {
mp3File.SetAlbum(album)
}
if genre != "" {
@ -70,15 +68,15 @@ func set()*cobra.Command{
return cmd
}
func main(){
func main() {
cmd := &cobra.Command{
Short: "",
}
showCmd := &cobra.Command{
Use: "show",
Use: "show",
Short: "show [file]",
Args: cobra.ExactArgs(1),
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
if err := show(args[0]); err != nil {
panic(err)
@ -87,4 +85,4 @@ func main(){
}
cmd.AddCommand(showCmd, set())
cmd.Execute()
}
}

View File

@ -11,24 +11,24 @@ import (
)
type Client struct {
User string
ID string
User string
ID string
msgChan chan string
}
func (c *Client)Write(msg string){
func (c *Client) Write(msg string) {
c.msgChan <- msg
}
type NServer struct {
notifier *notify.Notifier
conn net.Conn
flusher http.Flusher
conn net.Conn
flusher http.Flusher
}
var ch = make(chan string)
func (n *NServer)Get(c *gin.Context){
func (n *NServer) Get(c *gin.Context) {
user := c.Query("user")
id := c.Query("client")
if user == "" || id == "" {
@ -70,8 +70,8 @@ func (n *NServer)Get(c *gin.Context){
// time.Sleep(100*time.Second)
}
func (n *NServer)Run(){
ticker := time.NewTicker(2*time.Second)
func (n *NServer) Run() {
ticker := time.NewTicker(2 * time.Second)
for t := range ticker.C {
str := fmt.Sprintf("data: %v\n\n", t.Format("2006-01-02 15:04:05"))
fmt.Println("send data to n")
@ -87,7 +87,7 @@ func (n *NServer)Run(){
}
}
func main(){
func main() {
n := NServer{
notifier: notify.NewNotifier(),
}
@ -123,4 +123,4 @@ func main(){
// }
// }()
// log.Fatal(http.ListenAndServe(":18000", nil))
// }
// }

View File

@ -11,12 +11,12 @@ import (
)
type Consumer struct {
UserID string
UserID string
ClientID string
conn io.WriteCloser
conn io.WriteCloser
}
func NewConsumer(c *gin.Context)(*Consumer, error){
func NewConsumer(c *gin.Context) (*Consumer, error) {
user := c.Query("user")
clientID := c.Query("client")
if clientID == "" {
@ -27,15 +27,15 @@ func NewConsumer(c *gin.Context)(*Consumer, error){
return nil, err
}
consumer := Consumer{
UserID: user,
UserID: user,
ClientID: clientID,
conn: conn,
conn: conn,
}
useGzip := false
if strings.Contains(c.GetHeader("Accept-Encoding"), "gzip") {
useGzip = true
}
err = consumer.init(useGzip)
if err != nil {
conn.Close()
@ -43,12 +43,12 @@ func NewConsumer(c *gin.Context)(*Consumer, error){
return &consumer, err
}
func (c *Consumer)Write(msg string)error{
func (c *Consumer) Write(msg string) error {
_, err := c.conn.Write([]byte(fmt.Sprintf("data: %s\n\n", msg)))
return err
}
func (c *Consumer)init(gz bool)error{
func (c *Consumer) init(gz bool) error {
if err := c.Write("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n"); err != nil {
return err
}
@ -63,4 +63,4 @@ func (c *Consumer)init(gz bool)error{
}
return c.Write("\r\n")
return nil
}
}

View File

@ -1,6 +1,6 @@
package notify
type Message struct {
User string
User string
Message string
}
}

View File

@ -8,60 +8,60 @@ import (
)
type Notifier struct {
Consumers map[string]*Consumer
userClients map[string][]string
lock sync.Mutex
Consumers map[string]*Consumer
userClients map[string][]string
lock sync.Mutex
consumerChan chan *Consumer
messageChan chan Message
messageChan chan Message
}
func NewNotifier()*Notifier{
func NewNotifier() *Notifier {
return &Notifier{
Consumers: make(map[string]*Consumer),
lock: sync.Mutex{},
Consumers: make(map[string]*Consumer),
lock: sync.Mutex{},
consumerChan: make(chan *Consumer),
messageChan: make(chan Message),
userClients: map[string][]string{},
messageChan: make(chan Message),
userClients: map[string][]string{},
}
}
func (n *Notifier)AddConsumer(c *gin.Context)error{
func (n *Notifier) AddConsumer(c *gin.Context) error {
consumer, err := NewConsumer(c)
if err != nil{
if err != nil {
return err
}
go func () {
go func() {
n.consumerChan <- consumer
}()
return nil
}
func (n *Notifier)recieveMessage(ctx context.Context){
func (n *Notifier) recieveMessage(ctx context.Context) {
for {
select{
case <- ctx.Done():
select {
case <-ctx.Done():
return
case msg := <- n.messageChan:
case msg := <-n.messageChan:
n.notify(msg)
}
}
}
func (n *Notifier)notify(msg Message){
func (n *Notifier) notify(msg Message) {
n.lock.Lock()
defer n.lock.Unlock()
clts, ok := n.userClients[msg.User];
if !ok || len(clts) == 0{
return
clts, ok := n.userClients[msg.User]
if !ok || len(clts) == 0 {
return
}
newClts := []string{}
for _, clt := range clts{
for _, clt := range clts {
client, ok := n.Consumers[clt]
if ok {
err := client.Write(msg.Message)
if err != nil {
delete(n.Consumers, clt)
}else{
} else {
newClts = append(newClts, clt)
}
}
@ -69,36 +69,36 @@ func (n *Notifier)notify(msg Message){
n.userClients[msg.User] = newClts
}
func (n *Notifier)recieveConsumer(ctx context.Context){
func (n *Notifier) recieveConsumer(ctx context.Context) {
for {
select{
case <- ctx.Done():
select {
case <-ctx.Done():
return
case c := <- n.consumerChan:
case c := <-n.consumerChan:
n.addConsumer(c)
}
}
}
func (n *Notifier)addConsumer(c *Consumer){
func (n *Notifier) addConsumer(c *Consumer) {
n.lock.Lock()
defer n.lock.Unlock()
n.Consumers[c.ClientID] = c
us := []string{}
if u, ok := n.userClients[c.UserID]; ok {
us=append(us, u...)
us = append(us, u...)
}
us=append(us, c.ClientID)
us = append(us, c.ClientID)
n.userClients[c.UserID] = us
}
func (n *Notifier)Run(ctx context.Context){
func (n *Notifier) Run(ctx context.Context) {
go n.recieveConsumer(ctx)
n.recieveMessage(ctx)
}
func (n *Notifier)SendMessage(user, msg string){
go func () {
func (n *Notifier) SendMessage(user, msg string) {
go func() {
n.messageChan <- Message{User: user, Message: msg}
}()
}
}

View File

@ -15,7 +15,7 @@ var (
clientSecret = "cbfd6e04-a51c-4982-a25b-7aaba4f30c81"
redirectURL = "http://localhost:8181/demo/callback"
state = "somestate"
state = "somestate"
)
func handleRedirect(w http.ResponseWriter, r *http.Request) {

View File

@ -217,119 +217,117 @@ func (a *AliOSS) CheckFileVersion(obj string, info os.FileInfo) (bool, error) {
return info.ModTime().Unix() >= modifiedAt, nil
}
// const host = "http://testspeed.xk.design"
const MAX = 300
type file struct{
Name string
Width int
type file struct {
Name string
Width int
Height int
Src string
Src string
}
var test1 = []file{
{
Name: "test4k.jpg",
Width: 0,
Name: "test4k.jpg",
Width: 0,
Height: 0,
Src: "test4k.jpg",
Src: "test4k.jpg",
},
{
Name: "test2k.jpg",
Width: 2590,
Name: "test2k.jpg",
Width: 2590,
Height: 1619,
Src: "test4k.jpg",
Src: "test4k.jpg",
},
{
Name: "test1k.jpg",
Width: 1831,
Name: "test1k.jpg",
Width: 1831,
Height: 1144,
Src: "test4k.jpg",
Src: "test4k.jpg",
},
{
Name: "test600.jpg",
Width: 647,
Name: "test600.jpg",
Width: 647,
Height: 404,
Src: "test4k.jpg",
Src: "test4k.jpg",
},
{
Name: "test1of10.jpg",
Width: 384,
Name: "test1of10.jpg",
Width: 384,
Height: 240,
Src: "test4k.jpg",
Src: "test4k.jpg",
},
}
var test2 = []file{
{
Name: "8ktestsrc.jpeg",
Width: 7680,
Name: "8ktestsrc.jpeg",
Width: 7680,
Height: 4320,
Src: "8ktestsrc.jpeg",
Src: "8ktestsrc.jpeg",
},
{
Name: "8ktest3k.jpeg",
Width: 2730,
Name: "8ktest3k.jpeg",
Width: 2730,
Height: 1536,
Src: "8ktestsrc.jpeg",
Src: "8ktestsrc.jpeg",
},
{
Name: "8ktest1080.jpeg",
Width: 1930,
Name: "8ktest1080.jpeg",
Width: 1930,
Height: 1086,
Src: "8ktestsrc.jpeg",
Src: "8ktestsrc.jpeg",
},
{
Name: "8ktest682.jpeg",
Width: 682,
Name: "8ktest682.jpeg",
Width: 682,
Height: 384,
Src: "8ktestsrc.jpeg",
Src: "8ktestsrc.jpeg",
},
{
Name: "8ktest400.jpeg",
Width: 400,
Name: "8ktest400.jpeg",
Width: 400,
Height: 225,
Src: "8ktestsrc.jpeg",
Src: "8ktestsrc.jpeg",
},
{
Name: "8ktest300.jpeg",
Width: 300,
Name: "8ktest300.jpeg",
Width: 300,
Height: 300,
Src: "8ktestsrc.jpeg",
Src: "8ktestsrc.jpeg",
},
}
func NewRequest(url string)(*http.Request, error){
func NewRequest(url string) (*http.Request, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req.Header.Add("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
req.Header.Add("Accept-Encoding","gzip, deflate")
req.Header.Add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.56")
req.Header.Add("Accept-Language","zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
req.Header.Add("Cache-Control","no-cache")
req.Header.Add("Connection"," keep-alive")
req.Header.Add("Cookie"," Hm_lvt_2e2c80c1bd8a51afc2d7de641330a397=1669089775,1669615598,1669704782,1669875251; Hm_lpvt_2e2c80c1bd8a51afc2d7de641330a397=1669964998")
req.Header.Add("Host"," test-pic.xk.design")
req.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
req.Header.Add("Accept-Encoding", "gzip, deflate")
req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.56")
req.Header.Add("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
req.Header.Add("Cache-Control", "no-cache")
req.Header.Add("Connection", " keep-alive")
req.Header.Add("Cookie", " Hm_lvt_2e2c80c1bd8a51afc2d7de641330a397=1669089775,1669615598,1669704782,1669875251; Hm_lpvt_2e2c80c1bd8a51afc2d7de641330a397=1669964998")
req.Header.Add("Host", " test-pic.xk.design")
// req.Header.Add("If-Modified-Since"," Fri, 02 Dec 2022 06:31:28 GMT")
// req.Header.Add("If-None-Match","\"4B8579BA5E07DD57405973606E777476\"")
// req.Header.Add("Upgrade-Insecure-Requests","1")
return req, nil
}
func test(f file, count int, host string){
func test(f file, count int, host string) {
fmt.Printf("begin normal testing for %s\n", f.Name)
startedAt := time.Now().UnixMilli()
errCount := 0
costMS := []int64{}
for i := 0; i < count; i ++ {
for i := 0; i < count; i++ {
req, err := NewRequest(host + "/" + f.Name)
if err != nil {
errCount ++
errCount++
continue
}
client := &http.Client{}
@ -355,13 +353,13 @@ func test(f file, count int, host string){
statistics(costMS)
}
func testResize(f file, count int, host string)(int64, int64, int64){
func testResize(f file, count int, host string) (int64, int64, int64) {
fmt.Printf("begin resize testing for %s\n", f.Name)
startedAt := time.Now().UnixMilli()
errCount := 0
costMS := []int64{}
for i := 0; i < count; i ++ {
query := "?x-oss-process=image/resize,m_lfit,w_"+strconv.Itoa(f.Width) + ",h_" + strconv.Itoa(f.Height)
for i := 0; i < count; i++ {
query := "?x-oss-process=image/resize,m_lfit,w_" + strconv.Itoa(f.Width) + ",h_" + strconv.Itoa(f.Height)
if f.Height == 0 || f.Width == 0 {
query = ""
}
@ -396,7 +394,7 @@ func testResize(f file, count int, host string)(int64, int64, int64){
return statistics(costMS)
}
func filelist(dir string)([]string, error){
func filelist(dir string) ([]string, error) {
fis, err := os.ReadDir(dir)
if err != nil {
return nil, err
@ -410,20 +408,19 @@ func filelist(dir string)([]string, error){
return fs, nil
}
func case3(dir string, ak string, sk string, count int, host string)error{
func case3(dir string, ak string, sk string, count int, host string) error {
files, err := filelist(dir)
if err != nil {
return err
}
alioss := NewAliOSS("oss-cn-hangzhou.aliyuncs.com", ak,sk, "oxslmimg")
alioss := NewAliOSS("oss-cn-hangzhou.aliyuncs.com", ak, sk, "oxslmimg")
alioss.Init()
avgmap := make(map[string][]string)
p95map := make(map[string][]string)
for _, f := range files {
err = alioss.UploadFile(f, path.Join(dir,f))
err = alioss.UploadFile(f, path.Join(dir, f))
if err != nil {
fmt.Println("upload failed:", err, f, path.Join(dir,f))
fmt.Println("upload failed:", err, f, path.Join(dir, f))
continue
}
avgmap[f] = []string{}
@ -446,7 +443,7 @@ func case3(dir string, ak string, sk string, count int, host string)error{
return nil
}
func avg(data []int64)int64{
func avg(data []int64) int64 {
if len(data) == 0 {
return 0
}
@ -454,7 +451,7 @@ func avg(data []int64)int64{
for _, i := range data {
total = total + i
}
return total/int64(len(data))
return total / int64(len(data))
}
type SortInt64 []int64
@ -463,44 +460,44 @@ func (a SortInt64) Len() int { return len(a) }
func (a SortInt64) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a SortInt64) Less(i, j int) bool { return a[i] < a[j] }
func percent50(data []int64)int64{
func percent50(data []int64) int64 {
if len(data) == 0 {
return 0
}
i := int(float64(len(data)) * 0.5 )
i := int(float64(len(data)) * 0.5)
if i == len(data) {
return 0
}
return data[i]
}
func percent90(data []int64)int64{
func percent90(data []int64) int64 {
if len(data) == 0 {
return 0
}
i := int(float64(len(data)) * 0.9 )
i := int(float64(len(data)) * 0.9)
if i == len(data) {
return 0
}
return data[i]
}
func percent95(data []int64)int64{
func percent95(data []int64) int64 {
if len(data) == 0 {
return 0
}
i := int(float64(len(data)) * 0.95 )
i := int(float64(len(data)) * 0.95)
if i == len(data) {
return 0
}
return data[i]
}
func max(data []int64)int64{
func max(data []int64) int64 {
return data[len(data)-1]
}
func statistics(data []int64)(int64, int64, int64){
func statistics(data []int64) (int64, int64, int64) {
a := avg(data)
sort.Sort(SortInt64(data))
m := percent50(data)
@ -511,7 +508,7 @@ func statistics(data []int64)(int64, int64, int64){
return a, p95, ma
}
func main(){
func main() {
var tcase, count int
var host, ak, sk, dir string
flag.IntVar(&tcase, "case", 1, "which test case to use")
@ -519,20 +516,20 @@ func main(){
flag.StringVar(&host, "host", "http://testspeed.xk.design", "access host")
flag.StringVar(&ak, "ak", "", "access key")
flag.StringVar(&sk, "sk", "", "access secret")
flag.StringVar(&dir , "dir", "", "img path")
flag.StringVar(&dir, "dir", "", "img path")
flag.Parse()
switch tcase {
case 1:
for _, f := range test1 {
test(f, count, host)
testResize(f, count, host)
}
}
case 2:
for _, f := range test2 {
test(f, count, host)
testResize(f, count, host)
}
}
case 3:
case3(dir, ak, sk, count, host)
}
}
}

View File

@ -8,7 +8,7 @@ import (
"github.com/skip2/go-qrcode"
)
func main(){
func main() {
code, err := qrcode.New("http://weixin.qq.com/q/02vEhthpJ1fqD1mfbvxzcy", qrcode.High)
if err != nil {
log.Fatal(err)
@ -22,4 +22,4 @@ func main(){
if err != nil {
log.Fatal(err)
}
}
}

View File

@ -12,8 +12,8 @@ import (
)
const (
Send = "二进制消息 2.6 kB"
Recieve = "二进制消息 3.9 kB"
Send = "二进制消息 2.6 kB"
Recieve = "二进制消息 3.9 kB"
Broadcast = "二进制消息 16 B"
)
@ -23,7 +23,7 @@ type message struct {
Time int64
}
func time2int64(t string)int64{
func time2int64(t string) int64 {
strs := strings.Split(t, ":")
if len(strs) != 3 {
return 0
@ -36,7 +36,7 @@ func time2int64(t string)int64{
}
second := seconds[0]
mill := seconds[1]
ms, err := strconv.ParseInt(mill, 10, 64)
if err != nil {
log.Println(err)
@ -47,23 +47,23 @@ func time2int64(t string)int64{
log.Println(err)
return 0
}
ms = ms + h *3600*1000
ms = ms + h*3600*1000
m, err := strconv.ParseInt(minute, 10, 64)
if err != nil {
log.Println(err)
return 0
}
ms = ms + m * 60 *1000
ms = ms + m*60*1000
s, err := strconv.ParseInt(second, 10, 64)
if err != nil {
log.Println(err)
return 0
}
ms = ms + s *1000
ms = ms + s*1000
return ms
}
func readdelay(file string)([]message, error){
func readdelay(file string) ([]message, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
@ -84,14 +84,14 @@ func readdelay(file string)([]message, error){
switch {
case strings.Contains(line, Send):
t = 1
case strings.Contains(line, Recieve):
case strings.Contains(line, Recieve):
t = 2
case strings.Contains(line, Broadcast):
case strings.Contains(line, Broadcast):
t = 3
default:
msg := message{Type: t, Time: time2int64(line)}
switch t {
case 1 :
case 1:
res = append(res, msg)
case 2:
res = append(res, msg)
@ -101,7 +101,7 @@ func readdelay(file string)([]message, error){
}
}
func avg(delays ...int64)int64{
func avg(delays ...int64) int64 {
if len(delays) == 0 {
return 0
}
@ -109,10 +109,10 @@ func avg(delays ...int64)int64{
for _, d := range delays {
total = total + d
}
return total/int64(len(delays))
return total / int64(len(delays))
}
func main(){
func main() {
var file string
flag.StringVar(&file, "f", "delay.log", "ssss")
flag.Parse()
@ -134,4 +134,4 @@ func main(){
}
}
fmt.Println(avg(delays...))
}
}

View File

@ -1 +1 @@
package main
package main

View File

@ -1,30 +1,30 @@
package test
type Cmd interface{
Result()bool
Output()string
type Cmd interface {
Result() bool
Output() string
}
type cmd struct{
type cmd struct {
r bool
o string
}
func (c *cmd)exec(s string, args ...string){
func (c *cmd) exec(s string, args ...string) {
//....
// c.r = ...
//c.o = ...
}
func (c *cmd)Result()bool{
func (c *cmd) Result() bool {
return c.r
}
func (c *cmd)Output()string{
func (c *cmd) Output() string {
return c.o
}
func Exec(s string, args ...string)Cmd{
func Exec(s string, args ...string) Cmd {
c := &cmd{}
c.exec(s, args...)
return c

View File

@ -1,5 +1,5 @@
package main
func main(){
}
func main() {
}

View File

@ -6,17 +6,16 @@ import (
"net/http"
"os"
"github.com/gin-gonic/gin"
)
func run(dir, title, addr string)error{
func run(dir, title, addr string) error {
engine := gin.Default()
engine.LoadHTMLGlob(dir + "/*.tmpl")
engine.Static("/ui", dir)
engine.StaticFS("/SC", http.Dir(dir + "/SC"))
engine.StaticFS("/SC", http.Dir(dir+"/SC"))
engine.GET("/", func(ctx *gin.Context) {
dirs, _ := os.ReadDir(dir)
dirs, _ := os.ReadDir(dir)
files := []string{}
for _, d := range dirs {
if !d.IsDir() {
@ -36,14 +35,14 @@ func run(dir, title, addr string)error{
return engine.Run(addr)
}
func main(){
func main() {
var dir, title, addr string
flag.StringVar(&dir, "dir", "./", "service dir")
flag.StringVar(&title, "title", "无标题", "website title")
flag.StringVar(&addr,"addr", ":3000", "listen port")
flag.StringVar(&addr, "addr", ":3000", "listen port")
flag.Parse()
err := run(dir, title, addr)
if err != nil {
panic(err)
}
}
}

View File

@ -64,7 +64,7 @@ func (s *Server) handleGet(c *gin.Context) {
c.String(http.StatusOK, echoStr)
}
//关注
// 关注
func (s *Server) handlePost(c *gin.Context) {
data := wechat.FoucsRequest{}
err := c.BindXML(&data)
@ -107,7 +107,7 @@ func (s *Server) handleDelete(c *gin.Context) {
c.String(http.StatusOK, "success")
}
//@router /auth/login
// @router /auth/login
func (s *Server) login(c *gin.Context) {
code := c.Query("code")
if code == "" {
@ -153,7 +153,7 @@ func (s *Server) Run(addr string) error {
return engine.Run(addr)
}
//https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc39301065b66300c&redirect_uri=http://106.55.59.210:15043/auth/login&response_type=code&scope=snsapi_userinfo#wechat_redirect
// https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc39301065b66300c&redirect_uri=http://106.55.59.210:15043/auth/login&response_type=code&scope=snsapi_userinfo#wechat_redirect
// https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc39301065b66300c&redirect_uri=http%3A%2F%2F106.55.59.210%3A15043%2Fauth%2Flogin&response_type=code&scope=snsapi_userinfo&connect_redirect=1#wechat_redirect
func main() {
s, err := NewServer()

View File

@ -41,7 +41,7 @@ func (m *Message) Show() {
fmt.Println(string(data))
}
//////
// ////
type MessageEntity struct {
Signature string `form:"signature"`
Timestamp string `form:"timestamp"`
@ -66,19 +66,19 @@ type FoucsRequest struct {
}
/*
{
"subscribe": 1,
"openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M",
"language": "zh_CN",
"subscribe_time": 1382694957,
"unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL",
"remark": "",
"groupid": 0,
"tagid_list":[128,2],
"subscribe_scene": "ADD_SCENE_QR_CODE",
"qr_scene": 98765,
"qr_scene_str": ""
}
{
"subscribe": 1,
"openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M",
"language": "zh_CN",
"subscribe_time": 1382694957,
"unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL",
"remark": "",
"groupid": 0,
"tagid_list":[128,2],
"subscribe_scene": "ADD_SCENE_QR_CODE",
"qr_scene": 98765,
"qr_scene_str": ""
}
*/
type UserInfo struct {
Subscribe int `json:"subscribe"`

View File

@ -14,7 +14,7 @@ type Token struct {
ExpiresIn int64 `json:"expires_in"`
ExpiredAt int64 `json:"expiredAt"`
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
ErrMsg string `json:"errmsg"`
}
type Wechat struct {
@ -83,7 +83,7 @@ func (w *Wechat) SendText(to, text string) ([]byte, error) {
return data, err
}
func (w *Wechat)GetUserInfo(openID string)(*UserInfo, error){
func (w *Wechat) GetUserInfo(openID string) (*UserInfo, error) {
token, err := w.queryToken()
if err != nil {
return nil, err
@ -98,7 +98,7 @@ func (w *Wechat)GetUserInfo(openID string)(*UserInfo, error){
return &ui, err
}
func (w *Wechat)GetGrantToken(code string)(*GrantToken, error){
func (w *Wechat) GetGrantToken(code string) (*GrantToken, error) {
url := fmt.Sprintf("%s?%s&code=%s&grant_type=authorization_code", APIGetGrantToken, w.queryStr(), code)
data, err := curl.SimpleGet(url)
@ -109,24 +109,25 @@ func (w *Wechat)GetGrantToken(code string)(*GrantToken, error){
err = json.Unmarshal(data, &token)
return &token, err
}
//{"expire_seconds":"60","action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": '.$id.'}}}
type Scene struct{
// {"expire_seconds":"60","action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": '.$id.'}}}
type Scene struct {
Str string `json:"scene_str"`
}
type ActionInfo struct {
ActionInfo Scene `json:"scene"`
}
type qrCodeRequest struct{
ExpireSeconds int `json:"expire_seconds"`
Action string `json:"action_name"`
ActionInfo ActionInfo `json:"action_info"`
type qrCodeRequest struct {
ExpireSeconds int `json:"expire_seconds"`
Action string `json:"action_name"`
ActionInfo ActionInfo `json:"action_info"`
}
func (w *Wechat)CreateQRCode()(*Ticket, error){
func (w *Wechat) CreateQRCode() (*Ticket, error) {
req := qrCodeRequest{
ExpireSeconds: 3600,
Action: "QR_STR_SCENE",
Action: "QR_STR_SCENE",
ActionInfo: ActionInfo{
Scene{
Str: fmt.Sprintf("aaa%d", time.Now().UnixNano()),
@ -145,4 +146,4 @@ func (w *Wechat)CreateQRCode()(*Ticket, error){
ticket := Ticket{}
err = json.Unmarshal(data, &ticket)
return &ticket, err
}
}

View File

@ -24,7 +24,7 @@ func connectCluster() (*kubernetes.Clientset, error) {
config, err := clientcmd.BuildConfigFromFlags("", conf)
if err != nil {
return nil, err
}
}
clientset, err := kubernetes.NewForConfig(config)
return clientset, err
}

View File

@ -10,7 +10,7 @@ import (
"github.com/gomarkdown/markdown/parser"
)
func main(){
func main() {
file, err := os.Open("test.md")
if err != nil {
panic(err)
@ -28,11 +28,11 @@ func main(){
parser.Strikethrough |
parser.SpaceHeadings
opts := html.RendererOptions{
Flags: htmlFlags,
CSS: "http://www.bing89.com/css/markdown/fluent.css",
Flags: htmlFlags,
CSS: "http://www.bing89.com/css/markdown/fluent.css",
}
renderer := html.NewRenderer(opts)
parser := parser.NewWithExtensions(extensions)
html := markdown.ToHTML(data, parser, renderer)
fmt.Println(string(html))
}
}