Skip to content

Commit

Permalink
feat: Overall optimization and adjustments
Browse files Browse the repository at this point in the history
- Enhance error handling using xerror package
- Refactor code to utilize utility methods from x package
- Improve logging with xlog package
- Optimize type conversions using xcast package
- Enhance HTTP client with xhttpc package
- Unify code style and naming conventions
- Increase code reusability and maintainability
- Optimize performance and resource usage
- Strengthen security and error handling
- Improve documentation and comments
  • Loading branch information
seefs001 committed Sep 27, 2024
1 parent eef6bec commit 02e3167
Show file tree
Hide file tree
Showing 24 changed files with 2,162 additions and 837 deletions.
61 changes: 15 additions & 46 deletions examples/xai_example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,65 +2,32 @@ package main

import (
"context"
"time"

"github.com/seefs001/xox/x"
"github.com/seefs001/xox/xai"
"github.com/seefs001/xox/xenv"
"github.com/seefs001/xox/xlog"
)

func main() {
xenv.Load()
client := xai.NewOpenAIClient(xai.WithDebug(true))

// "MJ::JOB::upsample::1::32839cdf-9db3-4836-a50c-43df2fed88d5"
mj_response, err := client.ActMidjourney(context.Background(), xai.BuildMidjourneyActionContent(xai.MJJOBUpsample, "2", "32839cdf-9db3-4836-a50c-43df2fed88d5"), "1727458186093768")
if err != nil {
xlog.Error("Error generating image", "error", err)
return
}
xlog.Info("Image generation response:")
xlog.Info(x.MustToJSON(mj_response))
return

// mj_response, err := client.GenerateImageWithMidjourney(context.Background(), "cute cat girl --niji 5")
// if err != nil {
// xlog.Error("Error generating image", "error", err)
// return
// }
// xlog.Info("Image generation response:")
// xlog.Info(x.MustToJSON(mj_response))
xlog.Info("Starting AI example")

for {
mj_status, err := client.GetMidjourneyStatus(context.Background(), mj_response.Result)
if err != nil {
xlog.Error("Error getting midjourney status", "error", err)
return
}
xlog.Info("Midjourney status response:")
xlog.Info(x.MustToJSON(mj_status))

if mj_status.Status == "SUCCESS" || mj_status.FailReason != "" {
break
}

time.Sleep(5 * time.Second)
}
xenv.Load()
xlog.Info("Environment variables loaded")

// return
client := xai.NewOpenAIClient(xai.WithDebug(true))
xlog.Info("OpenAI client created with debug mode enabled")

// Text generation (non-streaming)
xlog.Info("Generating text using QuickGenerateText")
response, err := client.QuickGenerateText(context.Background(), []string{"Hello, world!"}, xai.WithTextModel(xai.ModelGPT4o))
if err != nil {
xlog.Error("Error generating text", "error", err)
return
}
xlog.Info("Text generation response:")
xlog.Info(response)
xlog.Info("Text generation response:", "response", response)

// Text generation (streaming)
xlog.Info("Streaming text generation:")
xlog.Info("Starting streaming text generation")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
textChan, errChan := client.QuickGenerateTextStream(ctx, []string{"Hello, world!"}, xai.WithTextModel(xai.ModelClaude35Sonnet))
Expand All @@ -75,7 +42,7 @@ func main() {
xlog.Info("Stream finished")
return
}
xlog.Info(text)
xlog.Info("Received text from stream", "text", text)
case err, ok := <-errChan:
if !ok {
return
Expand All @@ -93,22 +60,24 @@ func main() {
<-streamFinished

// Image generation
xlog.Info("Image generation:")
xlog.Info("Generating image")
imageURLs, err := client.GenerateImage(context.Background(), "A beautiful sunset over the ocean", xai.WithImageModel(xai.DefaultImageModel))
if err != nil {
xlog.Error("Error generating image", "error", err)
return
}
for i, url := range imageURLs {
xlog.Infof("Image %d URL: %s", i+1, url)
xlog.Info("Generated image URL", "index", i+1, "url", url)
}

// Embedding generation
xlog.Info("Embedding generation:")
xlog.Info("Creating embeddings")
embeddings, err := client.CreateEmbeddings(context.Background(), []string{"Hello, world!"}, xai.DefaultEmbeddingModel)
if err != nil {
xlog.Error("Error creating embeddings", "error", err)
return
}
xlog.Infof("Embedding for 'Hello, world!': %v", embeddings[0][:5]) // Print first 5 values of the embedding
xlog.Info("Embedding created", "embedding_sample", embeddings[0][:5]) // Print first 5 values of the embedding

xlog.Info("AI example completed")
}
23 changes: 23 additions & 0 deletions examples/xcli_example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,26 @@ import (
"strconv"

"github.com/seefs001/xox/xcli"
"github.com/seefs001/xox/xlog"
)

func main() {
xlog.Info("Starting CLI application example")

// Create the root command
rootCmd := xcli.NewCommand("app", "A comprehensive CLI application example", func(ctx context.Context, cmdCtx *xcli.CommandContext) error {
xlog.Info("Executing root command")
fmt.Println("Welcome to the CLI application. Use 'hello', 'goodbye', 'add', or 'version' subcommands.")
return nil
})

// Set version for the root command
rootCmd.SetVersion("1.0.0")
xlog.Info("Root command version set", "version", rootCmd.Version)

// Create a hello subcommand
helloCmd := xcli.NewCommand("hello", "Prints a greeting message", func(ctx context.Context, cmdCtx *xcli.CommandContext) error {
xlog.Info("Executing hello subcommand")
greeting := cmdCtx.Flags.Lookup("greeting").Value.String()
if len(cmdCtx.Args) < 1 {
return fmt.Errorf("name is required")
Expand All @@ -32,15 +38,19 @@ func main() {

// Add flags to the hello command
helloCmd.Flags.String("greeting", "Hello", "Custom greeting message")
xlog.Info("Added greeting flag to hello command")

// Set aliases for the hello command
helloCmd.SetAliases("hi", "greet")
xlog.Info("Set aliases for hello command", "aliases", []string{"hi", "greet"})

// Add the hello subcommand to the root command
rootCmd.AddSubcommand(helloCmd)
xlog.Info("Added hello subcommand to root command")

// Create a goodbye subcommand
goodbyeCmd := xcli.NewCommand("goodbye", "Prints a farewell message", func(ctx context.Context, cmdCtx *xcli.CommandContext) error {
xlog.Info("Executing goodbye subcommand")
farewell := cmdCtx.Flags.Lookup("farewell").Value.String()
if len(cmdCtx.Args) < 1 {
return fmt.Errorf("name is required")
Expand All @@ -52,12 +62,15 @@ func main() {

// Add flags to the goodbye command
goodbyeCmd.Flags.String("farewell", "Goodbye", "Custom farewell message")
xlog.Info("Added farewell flag to goodbye command")

// Add the goodbye subcommand to the root command
rootCmd.AddSubcommand(goodbyeCmd)
xlog.Info("Added goodbye subcommand to root command")

// Create an add subcommand for adding numbers
addCmd := xcli.NewCommand("add", "Adds two or more numbers", func(ctx context.Context, cmdCtx *xcli.CommandContext) error {
xlog.Info("Executing add subcommand")
if len(cmdCtx.Args) < 2 {
return fmt.Errorf("at least two numbers are required")
}
Expand All @@ -75,28 +88,38 @@ func main() {

// Add the add subcommand to the root command
rootCmd.AddSubcommand(addCmd)
xlog.Info("Added add subcommand to root command")

// Create a hidden debug subcommand
debugCmd := xcli.NewCommand("debug", "Prints debug information", func(ctx context.Context, cmdCtx *xcli.CommandContext) error {
xlog.Info("Executing debug subcommand")
fmt.Println("Debug mode activated")
return nil
})
debugCmd.SetHidden(true)
rootCmd.AddSubcommand(debugCmd)
xlog.Info("Added hidden debug subcommand to root command")

// Create a version subcommand
versionCmd := xcli.NewCommand("version", "Prints the application version", func(ctx context.Context, cmdCtx *xcli.CommandContext) error {
xlog.Info("Executing version subcommand")
fmt.Printf("App version: %s\n", rootCmd.Version)
return nil
})
rootCmd.AddSubcommand(versionCmd)
xlog.Info("Added version subcommand to root command")

// Enable color output
xcli.EnableColor(true)
xlog.Info("Enabled color output")

// Enable debug mode (for demonstration purposes)
xcli.EnableDebug(true)
xlog.Info("Enabled debug mode")

// Execute the root command
xlog.Info("Executing root command with arguments", "args", os.Args[1:])
xcli.Execute(rootCmd, os.Args[1:])

xlog.Info("CLI application example completed")
}
32 changes: 31 additions & 1 deletion examples/xhttp_example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@ import (
"time"

"github.com/seefs001/xox/xhttp"
"github.com/seefs001/xox/xlog"
"github.com/seefs001/xox/xmw"
)

// UserHandler handles requests for user information
func UserHandler(c *xhttp.Context) {
xlog.Info("Handling user request")
userID := c.GetParam("id")
if userID == "" {
xlog.Warn("Missing user ID in request")
c.JSON(http.StatusBadRequest, map[string]string{"error": "Missing user ID"})
return
}
Expand All @@ -24,40 +27,49 @@ func UserHandler(c *xhttp.Context) {
"name": fmt.Sprintf("User %s", userID),
}

xlog.Info("User data fetched", "user", user)
c.JSON(http.StatusOK, user)
}

// HeaderEchoHandler echoes back the received headers
func HeaderEchoHandler(c *xhttp.Context) {
xlog.Info("Handling header echo request")
headers := make(map[string]string)
for key, values := range c.Request.Header {
headers[key] = values[0]
}

xlog.Info("Echoing headers", "headers", headers)
c.JSON(http.StatusOK, headers)
}

// ContextValueHandler demonstrates using context values
func ContextValueHandler(c *xhttp.Context) {
xlog.Info("Handling context value request")
c.WithValue("key", "value")
val := c.GetContext().Value("key")
xlog.Info("Context value set and retrieved", "value", val)
c.JSON(http.StatusOK, map[string]string{"contextValue": val.(string)})
}

// ParamHandler demonstrates getting parameters as different types
func ParamHandler(c *xhttp.Context) {
xlog.Info("Handling param request")
id, err := c.GetParamInt("id")
if err != nil {
xlog.Warn("Invalid ID parameter", "error", err)
c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid ID"})
return
}

score, err := c.GetParamFloat("score")
if err != nil {
xlog.Warn("Invalid score parameter", "error", err)
c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid score"})
return
}

xlog.Info("Parameters parsed successfully", "id", id, "score", score)
c.JSON(http.StatusOK, map[string]interface{}{
"id": id,
"score": score,
Expand All @@ -66,51 +78,63 @@ func ParamHandler(c *xhttp.Context) {

// BodyHandler demonstrates decoding request body
func BodyHandler(c *xhttp.Context) {
xlog.Info("Handling body request")
var data map[string]interface{}
if err := c.GetBody(&data); err != nil {
xlog.Warn("Invalid request body", "error", err)
c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid request body"})
return
}

xlog.Info("Request body decoded", "data", data)
c.JSON(http.StatusOK, data)
}

// RedirectHandler demonstrates redirection
func RedirectHandler(c *xhttp.Context) {
xlog.Info("Handling redirect request")
c.Redirect(http.StatusFound, "/redirected")
}

// RedirectedHandler handles the redirected request
func RedirectedHandler(c *xhttp.Context) {
xlog.Info("Handling redirected request")
c.JSON(http.StatusOK, map[string]string{"message": "You've been redirected"})
}

// CookieHandler demonstrates setting and getting cookies
func CookieHandler(c *xhttp.Context) {
xlog.Info("Handling cookie request")
// Set a cookie
cookie := &http.Cookie{
Name: "example",
Value: "test",
Expires: time.Now().Add(24 * time.Hour),
}
c.SetCookie(cookie)
xlog.Info("Cookie set", "cookie", cookie)

// Get the cookie we just set
retrievedCookie, err := c.GetCookie("example")
if err != nil {
xlog.Error("Failed to retrieve cookie", "error", err)
c.JSON(http.StatusInternalServerError, map[string]string{"error": "Failed to retrieve cookie"})
return
}

xlog.Info("Cookie retrieved", "cookie", retrievedCookie)
c.JSON(http.StatusOK, map[string]string{"cookie_value": retrievedCookie.Value})
}

// NewHandler demonstrates using xmw middleware
func NewHandler(c *xhttp.Context) {
xlog.Info("Handling new request with xmw middleware")
c.JSON(http.StatusOK, map[string]string{"message": "This handler uses xmw middleware"})
}

func main() {
xlog.Info("Starting xhttp example server")

// Create a new ServeMux
mux := http.NewServeMux()

Expand All @@ -127,6 +151,8 @@ func main() {
// Add a new route that uses xmw middleware
mux.HandleFunc("/new", xhttp.Wrap(NewHandler))

xlog.Info("Routes set up successfully")

// Define middleware stack
middlewareStack := []xmw.Middleware{
xmw.Logger(xmw.LoggerConfig{
Expand All @@ -148,10 +174,14 @@ func main() {
}),
}

xlog.Info("Middleware stack defined")

// Apply middleware to the mux
handler := xmw.Use(mux, middlewareStack...)

xlog.Info("Middleware applied to mux")

// Start the server with the middleware-wrapped handler
fmt.Println("Server starting on :8080")
xlog.Info("Server starting on :8080")
log.Fatal(http.ListenAndServe(":8080", handler))
}
Loading

0 comments on commit 02e3167

Please sign in to comment.