分类 golang 下的文章

go build -gcflags '-m -l' main.go

通过编译参数可获知变量逃逸信息

func hello(x []byte) int {
    return len(x)
}

func main() {
    b := make([]byte, 10)
    b[3] = 'd'
    fmt.Println(hello(b))
}

# command-line-arguments
./main.go:5:12: x does not escape
./main.go:10:11: make([]byte, 10) does not escape
./main.go:12:13: ... argument does not escape
./main.go:12:19: hello(b) escapes to heap

偶然发现我的世界居然还有声音,听着感觉还蛮不错的,就想着写个程序提取出来吧。

我的世界资源目录:
%AppData%.minecraft\
~/Library/Application Support/minecraft/
~/.minecraft/

索引文件目录:
assets/indexes/

资源内容目录:
assets/objects/

package main

import (
    "encoding/json"
    "fmt"
    "io/fs"
    "log"
    "os"
    "path/filepath"
    "strings"
)

type AssetInfo struct {
    Hash string `json:"hash"`
    Size int    `json:"size"`
}

type Assets struct {
    Objects map[string]AssetInfo `json:"objects"`
}

func main() {
    var as Assets

    // 加载文件列表
    data, err := os.ReadFile("1.16.json")
    if err != nil {
        log.Fatal(err)
    }
    if err := json.Unmarshal(data, &as); err != nil {
        log.Fatal(err)
    }

    for k, v := range as.Objects {
        if !strings.HasSuffix(k, ".ogg") {
            continue
        }

        log.Println(k)

        // 创建文件夹
        dirpath, _ := filepath.Split(k)
        if err := os.MkdirAll(dirpath, os.ModePerm); err != nil {
            continue
        }

        // 复制文件
        data, err := os.ReadFile(fmt.Sprintf("../objects/%s/%s", v.Hash[:2], v.Hash))
        if err != nil {
            continue
        }
        if err := os.WriteFile(k, data, fs.ModePerm); err != nil {
            log.Println(err)
        }
    }
}

package main

/*
#cgo LDFLAGS: -framework CoreServices
#include <stdio.h>
#include <CoreServices/CoreServices.h>

void alert() {
    CFOptionFlags responseFlags = 0;
    CFUserNotificationDisplayAlert(20.0, 3, NULL, NULL, NULL, CFSTR("提示"), CFSTR("你有一只小毛驴,从来也不骑~~~"), CFSTR("确定"), NULL, NULL, &responseFlags);
}
*/
import "C"

func main() {
    C.alert()
}

golang 1.16 版提供了资源内嵌

import _ "embed"

//go:embed hello.txt
var s string
print(s)


import _ "embed"

//go:embed hello.txt
var b []byte
print(string(b))


import "embed"

//go:embed hello.txt
var f embed.FS
data, _ := f.ReadFile("hello.txt")
print(string(data))


package server

import "embed"

// content holds our static web server content.
//go:embed image/* template/*
//go:embed html/index.html
var content embed.FS

func main() {
    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(content))))
    http.ListenAndServe(":8080", nil)
}

参考资料:
https://golang.org/pkg/embed/

package main

import (
    "fmt"

    "github.com/tealeg/xlsx"
)

func main() {
    xlFile, err := xlsx.OpenFile("Item.xlsx")
    if err != nil {
        panic(err.Error())
    }

    for _, v := range xlFile.Sheets[0].Rows {
        if len(v.Cells) > 0 {
            fmt.Printf("%s %s\n", v.Cells[1].String(), v.Cells[0].String())
        }
    }
}