Skip to content

Commit 00de321

Browse files
committed
Use Go templates instead of format strings
1 parent 52bb44c commit 00de321

File tree

3 files changed

+32
-12
lines changed

3 files changed

+32
-12
lines changed

commands/new_go.go

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,17 @@ import (
55
"os"
66
"path/filepath"
77
"strings"
8+
"text/template"
9+
10+
_ "embed"
811

912
"github.com/code-game-project/codegame-cli/external"
1013
"github.com/code-game-project/codegame-cli/input"
11-
"github.com/code-game-project/codegame-cli/templates"
1214
)
1315

16+
//go:embed templates/main.go.tmpl
17+
var goMainTemplate string
18+
1419
func newClientGo(projectName, serverURL, cgVersion string) error {
1520
err := createGoTemplate(projectName, serverURL)
1621
if err != nil {
@@ -42,7 +47,24 @@ func createGoTemplate(projectName, serverURL string) error {
4247
return err
4348
}
4449

45-
return os.WriteFile(filepath.Join(projectName, "main.go"), []byte(strings.ReplaceAll(fmt.Sprintf(templates.Go, serverURL), "$", "%")), 0644)
50+
tmpl, err := template.New("main.go").Parse(goMainTemplate)
51+
if err != nil {
52+
return err
53+
}
54+
55+
file, err := os.Create(filepath.Join(projectName, "main.go"))
56+
if err != nil {
57+
return err
58+
}
59+
defer file.Close()
60+
61+
type data struct {
62+
URL string
63+
}
64+
65+
return tmpl.Execute(file, data{
66+
URL: serverURL,
67+
})
4668
}
4769

4870
func installGoLibrary(projectName, cgVersion string) error {

commands/templates/main.go.tmpl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package main
2+
3+
func main() {
4+
socket, err := cg.NewSocket("{{.URL}}")
5+
if err != nil {
6+
log.Fatalf("failed to connect to server: %s", err)
7+
}
8+
}

templates/go.go

Lines changed: 0 additions & 10 deletions
This file was deleted.

0 commit comments

Comments
 (0)