export $PATH
go version
go: loc
main.go
go run .
doesn't work for mesudo snap install go --classic
, super easy:wget https://golang.org/dl/go1.22.3.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.22.3.linux-amd64.tar.gz
vim ~/.profile
export PATH=$PATH:/usr/local/go/binexport GOPATH=$HOME/goexport PATH=$PATH:$GOPATH/bin
source ~/.profile
go version
package mainimport "fmt"const path = "usr/bin"func separator() {fmt.Println("---")}func main() {var message string = "greetings"var age = 42var answer intrank := 5.4 // same as with var, but only inside functionsfmt.Printf("The message is \"%s\".\n", message)fmt.Printf("The message type is \"%T\".\n", message)separator()fmt.Printf("The age is %d.\n", age)fmt.Printf("The age type is \"%T\".\n", age)separator()fmt.Printf("The answer is %d.\n", answer)fmt.Printf("The answer type is \"%T\".\n", answer)separator()fmt.Printf("The rank is %f.\n", rank)fmt.Printf("The rank is %.2f.\n", rank)fmt.Printf("The rank type is \"%T\".\n", rank)separator()fmt.Printf("The constant path is \"%s\".\n", path)fmt.Printf("The constant path type is \"%T\".\n", path)}
package mainimport ("fmt""bufio""os""strings")func main() {reader := bufio.NewReader(os.Stdin)fmt.Print("What is your name? ")username, _ := reader.ReadString('\n')username = strings.TrimSpace(username)fmt.Printf("Your name is \"%s\".\n", username)}
getname
that you can type anywheregetname
that you can type anywhere/usr/local/bin
package mainimport ("fmt""bufio""os""strings""strconv")func main() {reader := bufio.NewReader(os.Stdin)fmt.Print("What is your name? ")username, _ := reader.ReadString('\n')username = strings.TrimSpace(username)fmt.Printf("Your name is \"%s\".\n", username)fmt.Print("What is your age? ")ageString, _ := reader.ReadString('\n')ageFloat, err := strconv.ParseFloat(strings.TrimSpace(ageString), 64)if(err != nil) {fmt.Println(err)} else {fmt.Printf(`You age to 2 decimal places is %.2f.`, ageFloat)}}
package mainimport ("fmt""math")func main() {age := 34exactYears := 3.4newAge := float64(age) + exactYearsfmt.Printf("we added %d and %f and got %f\n", age, exactYears, newAge)fmt.Printf("we added %v and %v and got %v\n", age, exactYears, newAge)fmt.Printf("we added %v years which rounded is %v years", exactYears, math.Round(exactYears))}
package mainimport ("fmt""time")func main() {now := time.Now()launchDateTime := time.Date(2009, time.November, 10, 23, 0,0,0,time.UTC)fmt.Printf("Time is %v\n", now)fmt.Printf("Go launched at %v\n", launchDateTime)fmt.Printf("Go launched at %v\n", launchDateTime.Format(time.ANSIC))fmt.Printf("Go launched at %v\n", launchDateTime.Format(time.RFC1123))}
var p *int
is a pointerpackage mainimport "fmt"func printValues(i int, p *int) {fmt.Printf("The age is %d\n", i)fmt.Printf("The pointer is %d\n", p)fmt.Printf("The pointer points to the value %d\n", *p)}func main() {age := 34pAge := &ageprintValues(age, pAge)*pAge += 1fmt.Println("--- VALUE UNDER POINTER CHANGED")printValues(age, pAge)}
type Product
package mainimport "fmt"func main() {emp := Employee{"Hans", "Hansrodt", 34}Separator()fmt.Println(emp)fmt.Printf("Employee: %v\n", emp)fmt.Printf("Employee: %+v\n", emp)Separator()fmt.Printf("The employee %v is %v years old.\n", emp.FirstName + " " + emp.LastName, emp.Age)emp.Age = emp.Age + 10Separator()fmt.Printf("The employee %v is %v years old.\n", emp.FirstName + " " + emp.LastName, emp.Age)}type Employee struct {FirstName stringLastName stringAge int}
package mainimport "fmt"func main() {appState := "offline"if appState == "online" {fmt.Println("app is online")} else if appState == "offline"{fmt.Println("app is OFFLINE")} else {fmt.Println("app state uncertain")}}
// random numberdow := rand.Intn(7) + 1fmt.Println("Day", dow)var result stringswitch dow {case 1:result = "Sunday"case 2:result = "Monday"case 3:result = "Tuesday"default:result = "(some other day)"}
package mainimport ("encoding/json""fmt""net/http""strconv")func main() {port := 7788http.HandleFunc("/languages", func(w http.ResponseWriter, r *http.Request) {w.Header().Set("Access-Control-Allow-Origin", "*")w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")w.Header().Set("Access-Control-Allow-Headers", "Content-Type")w.Header().Set("Content-Type", "application/json")json.NewEncoder(w).Encode([]string{"C#", "Java", "Ruby", "Python", "JavaScript"})})fmt.Printf("listening at http://localhost:%v/languages\n", port)http.ListenAndServe(":"+strconv.Itoa(port), nil)}
import { useEffect, useState } from "react";function App() {const [languages, setLanguages] = useState<string[]>([]);useEffect(() => {(async () => {const response = await fetch("http://localhost:7788/languages");const _languages = await response.json();setLanguages(_languages);})();}, []);return (<div className="App"><h1>Frontend Test</h1><p>There are {languages.length} languages:</p><ul>{languages.map((language, index) => {return <li key={index}>{language}</li>;})}</ul></div>);}export default App;
package mainimport ("fmt""io""os""path/filepath")const dirName = "output"func createTextFile(idCode, content string) {err := os.MkdirAll(dirName, 0755)pathAndFileName := filepath.Join(dirName, idCode+".txt")file, err := os.Create(pathAndFileName)checkError(err)_, err = io.WriteString(file, content)checkError(err)defer file.Close()}func readTextFile(idCode string) {pathAndFileName := filepath.Join(dirName, idCode+".txt")data, err := os.ReadFile(pathAndFileName)checkError(err)fmt.Printf(`>>> %s
`, pathAndFileName, data)}func main() {colors := []string{"red", "blue", "yellow", "green"}for _, color := range colors {createTextFile(color, fmt.Sprintf("This is content about the color %s.", color))}readTextFile("yellow")}
package mainimport ("fmt""io""net/http")const url = "https://edwardtanguay.vercel.app/share/skills.json"func main() {resp, err := http.Get(url)checkError(err)fmt.Printf("Response type: %T\n", resp)defer resp.Body.Close()bytes, err := io.ReadAll(resp.Body)checkError(err)content := string(bytes)fmt.Print(content)}
go run main.go tools.go
package mainimport ("fmt""io""os""path/filepath")const outputDirName = "output"func separator() {fmt.Println("---")}func checkError(err error) {if err != nil {panic(err)}}func createTextFile(fileName, content string) {err := os.MkdirAll(outputDirName, 0755)pathAndFileName := filepath.Join(outputDirName, fileName)file, err := os.Create(pathAndFileName)checkError(err)_, err = io.WriteString(file, content)checkError(err)defer file.Close()}func getHtmlBoilerplateBegin(title string) string {return `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>` + title + `</title><style>* {margin: 0;padding: 0;box-sizing: border-box;}body {font-family: monospace;line-height: 1.5;padding: 1rem;}h2 {font-size: 1.2rem;margin-top: .3rem;}p {font-size: 1rem;font-style: italic;}a {color: #333;}</style></head><body>`}func getHtmlBoilerplateEnd() string {return `</body></html>`}
package mainimport ("encoding/json""fmt""io""net/http")const url = "https://edwardtanguay.vercel.app/share/skills.json"func main() {resp, err := http.Get(url)checkError(err)defer resp.Body.Close()bytes, err := io.ReadAll(resp.Body)checkError(err)json := string(bytes)skills := convertJsonToSkills(json)htmlContent := convertSkillsToHtml(skills)createTextFile("skills.html", htmlContent)}func convertSkillsToHtml(skills []Skill) string {html := ""title := "Skills"html += getHtmlBoilerplateBegin(title)html += fmt.Sprintf("<h1>%s</h1>", title)for _, skill := range skills {html += fmt.Sprintf("<h2><a target=\"_blank\" href=\"%s\">%s</a></h2>\n", skill.Url, skill.Name)html += fmt.Sprintf("<p>%s</p>\n", skill.Description)html += fmt.Sprintf("\n")}html += getHtmlBoilerplateEnd()return html}func convertJsonToSkills(content string) []Skill {var skills []Skillerr := json.Unmarshal([]byte(content), &skills)checkError(err)return skills}type Skill struct {IdCode string `json:"idCode"`Name string `json:"name"`Url string `json:"url"`Description string `json:"description"`}