chore: use go generate

This commit is contained in:
Jacky 2025-04-17 14:27:03 +00:00
parent 61ff392c5c
commit 82da0ef05e
No known key found for this signature in database
GPG key ID: 215C21B10DF38B4D
20 changed files with 151 additions and 363 deletions

View file

@ -15,7 +15,7 @@ full_bin = "APP_ENV=dev APP_USER=air ./tmp/main"
# Watch these filename extensions.
include_ext = ["go", "tpl", "tmpl", "html", "toml", "po", "conf"]
# Ignore these filename extensions or directories.
exclude_dir = ["assets", "tmp", "vendor", "app/node_modules", "upload", "docs", "resources", ".idea"]
exclude_dir = ["assets", "tmp", "vendor", "app/node_modules", "upload", "docs", "resources", ".idea", "cmd"]
# Watch these directories if you specified.
include_dir = []
# Exclude files.

2
.vscode/tasks.json vendored
View file

@ -84,7 +84,7 @@
{
"label": "Go Generate",
"type": "shell",
"command": "./gen.sh",
"command": "go generate",
"presentation": {
"panel": "new"
},

View file

@ -4,7 +4,7 @@
const notifications: Record<string, { title: () => string, content: (args: any) => string }> = {
// cluster module notifications
// general module notifications
'Reload Remote Nginx Error': {
title: () => $gettext('Reload Remote Nginx Error'),
content: (args: any) => $gettext('Reload Nginx on %{node} failed, response: %{resp}', args),
@ -21,8 +21,6 @@ const notifications: Record<string, { title: () => string, content: (args: any)
title: () => $gettext('Restart Remote Nginx Success'),
content: (args: any) => $gettext('Restart Nginx on %{node} successfully', args),
},
// cert module notifications
'Certificate Expired': {
title: () => $gettext('Certificate Expired'),
content: (args: any) => $gettext('Certificate %{name} has expired', args),
@ -51,8 +49,6 @@ const notifications: Record<string, { title: () => string, content: (args: any)
title: () => $gettext('Sync Certificate Success'),
content: (args: any) => $gettext('Sync Certificate %{cert_name} to %{env_name} successfully', args),
},
// config module notifications
'Sync Config Error': {
title: () => $gettext('Sync Config Error'),
content: (args: any) => $gettext('Sync config %{config_name} to %{env_name} failed', args),
@ -69,8 +65,6 @@ const notifications: Record<string, { title: () => string, content: (args: any)
title: () => $gettext('Rename Remote Config Success'),
content: (args: any) => $gettext('Rename %{orig_path} to %{new_path} on %{env_name} successfully', args),
},
// site module notifications
'Delete Remote Site Error': {
title: () => $gettext('Delete Remote Site Error'),
content: (args: any) => $gettext('Delete site %{name} from %{node} failed', args),
@ -127,8 +121,6 @@ const notifications: Record<string, { title: () => string, content: (args: any)
title: () => $gettext('Save Remote Site Success'),
content: (args: any) => $gettext('Save site %{name} to %{node} successfully', args),
},
// stream module notifications
'Delete Remote Stream Error': {
title: () => $gettext('Delete Remote Stream Error'),
content: (args: any) => $gettext('Delete stream %{name} from %{node} failed', args),
@ -169,8 +161,6 @@ const notifications: Record<string, { title: () => string, content: (args: any)
title: () => $gettext('Save Remote Stream Success'),
content: (args: any) => $gettext('Save stream %{name} to %{node} successfully', args),
},
// user module notifications
'All Recovery Codes Have Been Used': {
title: () => $gettext('All Recovery Codes Have Been Used'),
content: (args: any) => $gettext('Please generate new recovery codes in the preferences immediately to prevent lockout.', args),

View file

@ -1,3 +1,4 @@
//go:generate go run . -project . -type ts -output ../../app/src/constants/errors -ignore-dirs .devcontainer,app,.github
package main
import "github.com/uozi-tech/cosy/errdef"

View file

@ -1,6 +0,0 @@
// This file is auto-generated by notification generator. DO NOT EDIT.
const configMap = {
}
export default configMap

View file

@ -1,3 +1,4 @@
//go:generate go run .
package main
import (
@ -8,9 +9,12 @@ import (
"os"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"text/template"
"github.com/uozi-tech/cosy/logger"
)
// Structure to hold extracted notifier information
@ -51,18 +55,26 @@ export default {{.Name | replaceSpaces}}Config
var externalNotifierRegex = regexp.MustCompile(`@external_notifier\(([a-zA-Z0-9 _]+)\)`)
func main() {
if err := GenerateExternalNotifiers(); err != nil {
logger.Init("release")
_, file, _, ok := runtime.Caller(0)
if !ok {
logger.Error("Unable to get the current file")
return
}
basePath := filepath.Join(filepath.Dir(file), "../../")
if err := GenerateExternalNotifiers(basePath); err != nil {
fmt.Printf("error generating external notifier configs: %v\n", err)
}
}
// GenerateExternalNotifiers generates TypeScript config files for external notifiers
func GenerateExternalNotifiers() error {
func GenerateExternalNotifiers(root string) error {
fmt.Println("Generating external notifier configs...")
// Notification package path
notificationPkgPath := "internal/notification"
outputDir := "app/src/views/preference/components/ExternalNotify"
notificationPkgPath := filepath.Join(root, "internal/notification")
outputDir := filepath.Join(root, "app/src/views/preference/components/ExternalNotify")
// Create output directory if it doesn't exist
if err := os.MkdirAll(outputDir, 0755); err != nil {
@ -82,7 +94,7 @@ func GenerateExternalNotifiers() error {
notifier, found := extractNotifierInfo(file)
if found {
notifiers = append(notifiers, notifier)
fmt.Printf("Found notifier: %s in %s\n", notifier.Name, file)
logger.Infof("Found notifier: %s in %s\n", notifier.Name, file)
}
}
@ -98,7 +110,7 @@ func GenerateExternalNotifiers() error {
return fmt.Errorf("error updating index.ts: %w", err)
}
fmt.Println("Generation completed successfully!")
logger.Info("Generation completed successfully!")
return nil
}
@ -110,7 +122,7 @@ func extractNotifierInfo(filePath string) (NotifierInfo, bool) {
// Parse the file
file, err := parser.ParseFile(fset, filePath, nil, parser.ParseComments)
if err != nil {
fmt.Printf("Error parsing file %s: %v\n", filePath, err)
logger.Errorf("Error parsing file %s: %v\n", filePath, err)
return NotifierInfo{}, false
}
@ -232,7 +244,7 @@ func generateTSConfig(notifier NotifierInfo, outputDir string) error {
return fmt.Errorf("error executing template: %w", err)
}
fmt.Printf("Generated TypeScript config for %s at %s\n", notifier.Name, outputFile)
logger.Infof("Generated TypeScript config for %s at %s\n", notifier.Name, outputFile)
return nil
}
@ -272,6 +284,6 @@ func updateIndexFile(notifiers []NotifierInfo, outputDir string) error {
return fmt.Errorf("error writing index.ts: %w", err)
}
fmt.Printf("Updated index.ts at %s\n", indexPath)
logger.Infof("Updated index.ts at %s\n", indexPath)
return nil
}

View file

@ -1,24 +1,35 @@
//go:generate go run .
package main
import (
"flag"
"fmt"
"path/filepath"
"runtime"
"github.com/0xJacky/Nginx-UI/model"
"github.com/0xJacky/Nginx-UI/settings"
"github.com/uozi-tech/cosy/logger"
cSettings "github.com/uozi-tech/cosy/settings"
"gorm.io/driver/sqlite"
"gorm.io/gen"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"log"
"path"
gormlogger "gorm.io/gorm/logger"
)
func main() {
logger.Init("release")
_, file, _, ok := runtime.Caller(0)
if !ok {
logger.Error("Unable to get the current file")
return
}
basePath := filepath.Join(filepath.Dir(file), "../../")
// specify the output directory (default: "./query")
// ### if you want to query without context constrain, set mode gen.WithoutContext ###
g := gen.NewGenerator(gen.Config{
OutPath: "query",
OutPath: filepath.Join(basePath, "query"),
Mode: gen.WithoutContext | gen.WithDefaultQuery,
//if you want the nullable field generation property to be pointer type, set FieldNullable true
FieldNullable: true,
@ -41,17 +52,17 @@ func main() {
flag.Parse()
cSettings.Init(confPath)
dbPath := path.Join(path.Dir(confPath), fmt.Sprintf("%s.db", settings.DatabaseSettings.Name))
dbPath := filepath.Join(filepath.Dir(confPath), fmt.Sprintf("%s.db", settings.DatabaseSettings.Name))
var err error
db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
Logger: gormlogger.Default.LogMode(gormlogger.Info),
PrepareStmt: true,
DisableForeignKeyConstraintWhenMigrating: true,
})
if err != nil {
log.Fatalln(err)
logger.Fatalf("failed to open database: %v", err)
}
g.UseDB(db)

View file

@ -1,3 +1,4 @@
//go:generate go run .
package main
import (
@ -9,6 +10,8 @@ import (
"path/filepath"
"strings"
"runtime"
"github.com/spf13/afero"
"github.com/spf13/afero/zipfs"
"github.com/uozi-tech/cosy/logger"
@ -16,19 +19,26 @@ import (
const (
repoURL = "https://github.com/go-acme/lego/archive/refs/heads/master.zip"
zipFile = "lego-master.zip"
configDir = "internal/cert/config"
)
func main() {
logger.Init("release")
if err := downloadAndExtract(); err != nil {
_, file, _, ok := runtime.Caller(0)
if !ok {
logger.Error("Unable to get the current file")
return
}
basePath := filepath.Join(filepath.Dir(file), "../../")
zipFile, err := downloadAndExtract()
if err != nil {
logger.Errorf("Error downloading and extracting: %v\n", err)
os.Exit(1)
}
if err := copyTomlFiles(); err != nil {
if err := copyTomlFiles(zipFile, basePath); err != nil {
logger.Errorf("Error copying TOML files: %v\n", err)
os.Exit(1)
}
@ -37,36 +47,36 @@ func main() {
}
// downloadAndExtract downloads the lego repository and extracts it
func downloadAndExtract() error {
func downloadAndExtract() (string, error) {
// Download the file
logger.Info("Downloading lego repository...")
resp, err := http.Get(repoURL)
if err != nil {
return err
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s", resp.Status)
return "", fmt.Errorf("bad status: %s", resp.Status)
}
// Create the file
out, err := os.Create(zipFile)
out, err := os.CreateTemp("", "lego-master.zip")
if err != nil {
return err
return "", err
}
defer out.Close()
// Write the body to file
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
return "", err
}
return nil
return out.Name(), nil
}
func copyTomlFiles() error {
func copyTomlFiles(zipFile, basePath string) error {
// Open the zip file
logger.Info("Extracting files...")
zipReader, err := zip.OpenReader(zipFile)
@ -78,7 +88,6 @@ func copyTomlFiles() error {
// Extract files
zfs := zipfs.New(&zipReader.Reader)
afero.Walk(zfs, "./lego-master/providers", func(path string, info os.FileInfo, err error) error {
// Skip directories
if info.IsDir() {
return nil
}
@ -93,7 +102,7 @@ func copyTomlFiles() error {
return err
}
// Write to the destination file
destPath := filepath.Join(configDir, info.Name())
destPath := filepath.Join(basePath, configDir, info.Name())
if err := os.WriteFile(destPath, data, 0644); err != nil {
return err
}

View file

@ -1,12 +1,16 @@
//go:generate go run .
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"runtime"
"strings"
"path/filepath"
"github.com/uozi-tech/cosy/logger"
"golang.org/x/net/html"
)
@ -14,15 +18,26 @@ type Directive struct {
Links []string `json:"links"`
}
const (
targetPath = "internal/nginx/nginx_directives.json"
nginxURL = "https://nginx.org/en/docs/dirindex.html"
)
func main() {
if len(os.Args) < 2 {
log.Println("Usage: go run . <output_file>")
logger.Init("release")
_, file, _, ok := runtime.Caller(0)
if !ok {
logger.Error("Unable to get the current file")
return
}
outputPath := os.Args[1]
basePath := filepath.Join(filepath.Dir(file), "../../")
outputPath := filepath.Join(basePath, targetPath)
// Fetch page content
resp, err := http.Get("https://nginx.org/en/docs/dirindex.html")
resp, err := http.Get(nginxURL)
if err != nil {
log.Println("[Error] fetching page:", err)
logger.Errorf("fetching page: %v", err)
return
}
defer resp.Body.Close()
@ -30,7 +45,7 @@ func main() {
// Parse HTML
doc, err := html.Parse(resp.Body)
if err != nil {
log.Println("[Error] parsing HTML:", err)
logger.Errorf("parsing HTML: %v", err)
return
}
@ -103,15 +118,15 @@ func main() {
// Write results to JSON file
jsonData, err := json.MarshalIndent(directives, "", " ")
if err != nil {
log.Println("[Error] marshaling JSON:", err)
logger.Errorf("marshaling JSON: %v", err)
return
}
err = os.WriteFile(outputPath, jsonData, 0644)
if err != nil {
log.Println("[Error] writing file:", err)
logger.Errorf("writing file: %v", err)
return
}
log.Printf("[OK] Successfully parsed %d directives and saved to %s\n", len(directives), outputPath)
logger.Infof("Successfully parsed %d directives and saved to %s\n", len(directives), targetPath)
}

View file

@ -1,3 +1,4 @@
//go:generate go run .
package main
import (
@ -7,7 +8,10 @@ import (
"go/token"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/uozi-tech/cosy/logger"
)
// Structure for notification function calls
@ -21,13 +25,20 @@ type NotificationCall struct {
// Directories to exclude
var excludeDirs = []string{
".devcontainer", ".github", ".idea", ".pnpm-store",
".vscode", "app", "query", "tmp",
".vscode", "app", "query", "tmp", "cmd",
}
// Main function
func main() {
// Start scanning from the current directory
root := "."
logger.Init("release")
// Start scanning from the project root
_, file, _, ok := runtime.Caller(0)
if !ok {
logger.Error("Unable to get the current file")
return
}
root := filepath.Join(filepath.Dir(file), "../../")
calls := []NotificationCall{}
// Scan all Go files
@ -38,7 +49,7 @@ func main() {
// Skip excluded directories
for _, dir := range excludeDirs {
if strings.HasPrefix(path, "./"+dir) || strings.HasPrefix(path, dir+"/") {
if strings.Contains(path, dir) {
if info.IsDir() {
return filepath.SkipDir
}
@ -55,14 +66,14 @@ func main() {
})
if err != nil {
fmt.Printf("Error walking the path: %v\n", err)
logger.Errorf("Error walking the path: %v\n", err)
return
}
// Generate a single TS file
generateSingleTSFile(calls)
generateSingleTSFile(root, calls)
fmt.Printf("Found %d notification calls\n", len(calls))
logger.Infof("Found %d notification calls\n", len(calls))
}
// Find notification function calls in Go files
@ -71,7 +82,7 @@ func findNotificationCalls(filePath string, calls *[]NotificationCall) {
fset := token.NewFileSet()
node, err := parser.ParseFile(fset, filePath, nil, parser.ParseComments)
if err != nil {
fmt.Printf("Error parsing %s: %v\n", filePath, err)
logger.Errorf("Error parsing %s: %v\n", filePath, err)
return
}
@ -165,12 +176,12 @@ func getStringValue(expr ast.Expr) string {
}
// Generate a single TypeScript file
func generateSingleTSFile(calls []NotificationCall) {
func generateSingleTSFile(root string, calls []NotificationCall) {
// Create target directory
targetDir := "app/src/components/Notification"
targetDir := filepath.Join(root, "app/src/components/Notification")
err := os.MkdirAll(targetDir, 0755)
if err != nil {
fmt.Printf("Error creating directory %s: %v\n", targetDir, err)
logger.Errorf("Error creating directory %s: %v\n", targetDir, err)
return
}
@ -237,9 +248,9 @@ func generateSingleTSFile(calls []NotificationCall) {
// Write file
err = os.WriteFile(tsFilePath, []byte(content.String()), 0644)
if err != nil {
fmt.Printf("Error writing TS file %s: %v\n", tsFilePath, err)
logger.Errorf("Error writing TS file %s: %v\n", tsFilePath, err)
return
}
fmt.Printf("Generated single TS file: %s with %d notifications\n", tsFilePath, len(calls))
logger.Infof("Generated single TS file: %s with %d notifications\n", tsFilePath, len(calls))
}

View file

@ -1,3 +1,4 @@
//go:generate go run .
package main
import (
@ -6,12 +7,14 @@ import (
"fmt"
"io"
"io/fs"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"strings"
"github.com/uozi-tech/cosy/logger"
)
type VersionInfo struct {
@ -21,54 +24,66 @@ type VersionInfo struct {
}
func main() {
logger.Init("release")
_, file, _, ok := runtime.Caller(0)
if !ok {
log.Print("Unable to get the current file")
logger.Error("Unable to get the current file")
return
}
basePath := path.Join(path.Dir(file), "../../")
basePath := filepath.Join(filepath.Dir(file), "../../")
versionFile, err := os.Open(path.Join(basePath, "app/dist/version.json"))
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
log.Print("\"dist/version.json\" not found, load from src instead")
logger.Error("\"dist/version.json\" not found, load from src instead")
versionFile, err = os.Open(path.Join(basePath, "app/src/version.json"))
}
if err != nil {
log.Fatal(err)
logger.Fatalf("Failed to open version.json: %v", err)
return
}
}
defer func(versionFile fs.File) {
err := versionFile.Close()
if err != nil {
log.Fatal(err)
}
}(versionFile)
defer versionFile.Close()
// Read the version.json file
data, err := io.ReadAll(versionFile)
if err != nil {
log.Fatalf("Failed to read version.json: %v", err)
logger.Fatalf("Failed to read version.json: %v", err)
}
// Parse the JSON data
var versionInfo VersionInfo
err = json.Unmarshal(data, &versionInfo)
if err != nil {
log.Fatalf("Failed to parse JSON: %v", err)
logger.Fatalf("Failed to parse JSON: %v", err)
}
// get current git commit hash
commitHash, err := getGitCommitHash(basePath)
if err != nil {
logger.Fatalf("Failed to get git commit hash: %v", err)
}
err = generateVersionGenGo(basePath, versionInfo, commitHash)
if err != nil {
logger.Fatalf("Failed to generate version.gen.go: %v", err)
}
}
func getGitCommitHash(basePath string) (string, error) {
cmd := exec.Command("git", "-C", basePath, "rev-parse", "HEAD")
commitHash, err := cmd.Output()
if err != nil {
log.Printf("Failed to get git commit hash: %v", err)
commitHash = []byte("")
return "", err
}
return strings.TrimRight(string(commitHash), "\r\n"), nil
}
func generateVersionGenGo(basePath string, versionInfo VersionInfo, commitHash string) error {
// Generate the version.gen.go file content
genContent := fmt.Sprintf(`// Code generated by cmd/version/generate.go; DO NOT EDIT.
@ -82,11 +97,12 @@ func init() {
}
`, versionInfo.Version, versionInfo.BuildId, versionInfo.TotalBuild, strings.TrimRight(string(commitHash), "\r\n"))
genPath := path.Join(basePath, "internal/version/version.gen.go")
err = os.WriteFile(genPath, []byte(genContent), 0644)
genPath := filepath.Join(basePath, "internal/version/version.gen.go")
err := os.WriteFile(genPath, []byte(genContent), 0644)
if err != nil {
log.Fatalf("Failed to write version.gen.go: %v", err)
return err
}
fmt.Println("version.gen.go has been generated successfully.")
logger.Info("version.gen.go has been generated successfully.")
return nil
}

17
gen.sh
View file

@ -1,17 +0,0 @@
# generate gen code
go run cmd/gen/generate.go -config app.ini
# generate error definitions
go run cmd/errdef/generate.go -project . -type ts -output ./app/src/constants/errors -ignore-dirs .devcontainer,app,.github
# parse nginx directive indexs
go run cmd/ngx_dir_index/ngx_dir_index.go ./internal/nginx/nginx_directives.json
# generate notification texts
go run cmd/notification/generate.go
# generate external notifier configs
go run cmd/external_notifier/generate.go
# generate lego config
go run cmd/lego_config/main.go

View file

@ -23,8 +23,7 @@ import (
cSettings "github.com/uozi-tech/cosy/settings"
)
//go:generate go run cmd/version/generate.go
//go:generate go generate ./cmd/...
func Program(confPath string) func(state overseer.State) {
return func(state overseer.State) {
defer logger.Sync()

34
package-lock.json generated
View file

@ -1,34 +0,0 @@
{
"name": "nginx-ui",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"dependencies": {
"@types/lodash-es": "^4.17.12",
"lodash-es": "^4.17.21"
}
},
"node_modules/@types/lodash": {
"version": "4.17.16",
"resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.16.tgz",
"integrity": "sha512-HX7Em5NYQAXKW+1T+FiuG27NGwzJfCX3s1GjOa7ujxZa52kjJLOr4FUxT+giF6Tgxv1e+/czV/iTtBw27WTU9g==",
"license": "MIT"
},
"node_modules/@types/lodash-es": {
"version": "4.17.12",
"resolved": "https://registry.npmjs.org/@types/lodash-es/-/lodash-es-4.17.12.tgz",
"integrity": "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==",
"license": "MIT",
"dependencies": {
"@types/lodash": "*"
}
},
"node_modules/lodash-es": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.21.tgz",
"integrity": "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==",
"license": "MIT"
}
}
}

View file

@ -1,6 +0,0 @@
{
"dependencies": {
"@types/lodash-es": "^4.17.12",
"lodash-es": "^4.17.21"
}
}

View file

@ -1,44 +0,0 @@
package test
import (
"fmt"
"runtime"
"testing"
"time"
"github.com/0xJacky/Nginx-UI/internal/analytic"
"github.com/shirou/gopsutil/v4/cpu"
"github.com/shirou/gopsutil/v4/disk"
"github.com/shirou/gopsutil/v4/load"
"github.com/shirou/gopsutil/v4/mem"
)
func TestGoPsutil(t *testing.T) {
fmt.Println("os:", runtime.GOOS)
fmt.Println("threads:", runtime.GOMAXPROCS(0))
v, _ := mem.VirtualMemory()
loadAvg, _ := load.Avg()
fmt.Println("loadavg", loadAvg.String())
fmt.Printf("Total: %v, Free:%v, UsedPercent:%f%%\n", v.Total, v.Free, v.UsedPercent)
cpuTimesBefore, _ := cpu.Times(false)
time.Sleep(1000 * time.Millisecond)
cpuTimesAfter, _ := cpu.Times(false)
threadNum := runtime.GOMAXPROCS(0)
fmt.Println(cpuTimesBefore[0].String(), "\n", cpuTimesAfter[0].String())
cpuUserUsage := (cpuTimesAfter[0].User - cpuTimesBefore[0].User) / (float64(1000*threadNum) / 1000)
cpuSystemUsage := (cpuTimesAfter[0].System - cpuTimesBefore[0].System) / (float64(1000*threadNum) / 1000)
fmt.Printf("%.2f, %.2f\n", cpuUserUsage*100, cpuSystemUsage*100)
diskUsage, _ := disk.Usage(".")
fmt.Println(diskUsage.String())
network, _ := analytic.GetNetworkStat()
fmt.Println(network)
time.Sleep(time.Second)
network, _ = analytic.GetNetworkStat()
fmt.Println(network)
}

View file

@ -1,55 +0,0 @@
package test
import (
"context"
"fmt"
"github.com/0xJacky/Nginx-UI/settings"
"errors"
"github.com/sashabaranov/go-openai"
"github.com/uozi-tech/cosy/sandbox"
"io"
"os"
"testing"
)
func TestChatGPT(t *testing.T) {
sandbox.NewInstance("../../app.ini", "sqlite").
Run(func(instance *sandbox.Instance) {
c := openai.NewClient(settings.OpenAISettings.Token)
ctx := context.Background()
req := openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo0301,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleUser,
Content: "帮我写一个 nginx 配置文件的示例",
},
},
Stream: true,
}
stream, err := c.CreateChatCompletionStream(ctx, req)
if err != nil {
fmt.Printf("CompletionStream error: %v\n", err)
return
}
defer stream.Close()
for {
response, err := stream.Recv()
if errors.Is(err, io.EOF) {
return
}
if err != nil {
fmt.Printf("Stream error: %v\n", err)
return
}
fmt.Printf("%v", response.Choices[0].Delta.Content)
_ = os.Stdout.Sync()
}
})
}

View file

@ -1,94 +0,0 @@
package test
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"fmt"
"io/ioutil"
"log"
"testing"
"github.com/go-acme/lego/v4/certcrypto"
"github.com/go-acme/lego/v4/certificate"
"github.com/go-acme/lego/v4/challenge/http01"
"github.com/go-acme/lego/v4/lego"
"github.com/go-acme/lego/v4/registration"
)
// You'll need a user or account type that implements acme.User
type MyUser struct {
Email string
Registration *registration.Resource
key crypto.PrivateKey
}
func (u *MyUser) GetEmail() string {
return u.Email
}
func (u MyUser) GetRegistration() *registration.Resource {
return u.Registration
}
func (u *MyUser) GetPrivateKey() crypto.PrivateKey {
return u.key
}
func TestLego(t *testing.T) {
// Create a user. New accounts need an email and private key to start.
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
log.Fatal(err)
}
myUser := MyUser{
Email: "me@jackyu.cn",
key: privateKey,
}
config := lego.NewConfig(&myUser)
// This CA URL is configured for a local dev instance of Boulder running in Dockerfile in a VM.
config.CADirURL = "https://acme-staging-v02.api.letsencrypt.org/directory"
config.Certificate.KeyType = certcrypto.RSA2048
// A client facilitates communication with the CA server.
client, err := lego.NewClient(config)
if err != nil {
log.Fatal(err)
}
err = client.Challenge.SetHTTP01Provider(http01.NewProviderServer("", "9180"))
if err != nil {
log.Fatal(err)
}
// New users will need to register
reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
if err != nil {
log.Fatal(err)
}
myUser.Registration = reg
request := certificate.ObtainRequest{
Domains: []string{"shanghai2.ojbk.me"},
Bundle: true,
}
certificates, err := client.Certificate.Obtain(request)
if err != nil {
log.Fatal(err)
}
// Each certificate comes back with the cert bytes, the bytes of the client's
// private key, and a certificate URL. SAVE THESE TO DISK.
fmt.Printf("%#v\n", certificates)
err = ioutil.WriteFile("fullchain.cer", certificates.Certificate, 0644)
if err != nil {
log.Fatal(err)
}
err = ioutil.WriteFile("private.key", certificates.PrivateKey, 0644)
if err != nil {
log.Fatal(err)
}
}

View file

@ -1,20 +0,0 @@
package test
import (
"fmt"
"log"
"os/exec"
"regexp"
"testing"
)
func TestGetNginx(t *testing.T) {
out, err := exec.Command("nginx", "-V").CombinedOutput()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", out)
r, _ := regexp.Compile("--conf-path=(.*)/(.*.conf)")
fmt.Println(r.FindStringSubmatch(string(out))[1])
}

View file

@ -47,7 +47,7 @@ cd ..
# Run go generate
echo "Generating Go code..."
go generate ./...
go generate
if [ $? -ne 0 ]; then
echo "Error: go generate failed"
exit 1