repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/fa/code/src/apps/ch.2.6/switch_type_check/main.go
fa/code/src/apps/ch.2.6/switch_type_check/main.go
package main import ( "fmt" "strconv" ) type Element interface{} type List []Element type Person struct { name string age int } func (p Person) String() string { return "(name: " + p.name + " - age: " + strconv.Itoa(p.age) + " years)" } func main() { list := make(List, 3) list[0] = 1 //an int list[1] = "Hello" //a string list[2] = Person{"Dennis", 70} for index, element := range list { switch value := element.(type) { case int: fmt.Printf("list[%d] is an int and its value is %d\n", index, value) case string: fmt.Printf("list[%d] is a string and its value is %s\n", index, value) case Person: fmt.Printf("list[%d] is a Person and its value is %s\n", index, value) default: fmt.Println("list[%d] is of a different type", index) } } }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/fa/code/src/apps/ch.2.6/reflection/main.go
fa/code/src/apps/ch.2.6/reflection/main.go
package main import ( "fmt" "reflect" ) func show_interface_none() { fmt.Println("\nshow_interface_none()") var a interface{} a = "string" a = 1 a = false fmt.Println("a =", a) } func show_reflection() { fmt.Println("\nshow_reflection()") var x float64 = 3.4 v := reflect.ValueOf(x) fmt.Println("type:", v.Type()) fmt.Println("kind is float64:", v.Kind() == reflect.Float64) fmt.Println("value:", v.Float()) p := reflect.ValueOf(&x) newX := p.Elem() newX.SetFloat(7.1) fmt.Println("newX =", newX) fmt.Println("newX float64() value:", newX.Float()) } func main() { show_interface_none() show_reflection() }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/fa/code/src/apps/ch.2.6/interface/main.go
fa/code/src/apps/ch.2.6/interface/main.go
package main import "fmt" type Human struct { name string age int phone string } type Student struct { Human school string loan float32 } type Employee struct { Human company string money float32 } func (h Human) SayHi() { fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone) } func (h Human) Sing(lyrics string) { fmt.Println("La la la la...", lyrics) } func (e Employee) SayHi() { fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name, e.company, e.phone) //Yes you can split into 2 lines here. } // Interface Men implemented by Human, Student and Employee type Men interface { SayHi() Sing(lyrics string) } func main() { mike := Student{Human{"Mike", 25, "222-222-XXX"}, "MIT", 0.00} paul := Student{Human{"Paul", 26, "111-222-XXX"}, "Harvard", 100} sam := Employee{Human{"Sam", 36, "444-222-XXX"}, "Golang Inc.", 1000} Tom := Employee{Human{"Sam", 36, "444-222-XXX"}, "Things Ltd.", 5000} // define interface i var i Men //i can store Student i = mike fmt.Println("This is Mike, a Student:") i.SayHi() i.Sing("November rain") //i can store Employee i = Tom fmt.Println("This is Tom, an Employee:") i.SayHi() i.Sing("Born to be wild") // slice of Men fmt.Println("Let's use a slice of Men and see what happens") x := make([]Men, 3) // these three elements are different types but they all implemented interface Men x[0], x[1], x[2] = paul, sam, mike for _, value := range x{ value.SayHi() } }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/fa/code/src/apps/ch.2.6/stringer_interface/main.go
fa/code/src/apps/ch.2.6/stringer_interface/main.go
package main import ( "fmt" "strconv" ) type Human struct { name string age int phone string } // Human implemented fmt.Stringer func (h Human) String() string { return "Name:" + h.name + ", Age:" + strconv.Itoa(h.age) + " years, Contact:" + h.phone } func main() { Bob := Human{"Bob", 39, "000-7777-XXX"} fmt.Println("This Human is : ", Bob) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/fa/code/src/apps/ch.2.6/type_check/main.go
fa/code/src/apps/ch.2.6/type_check/main.go
package main import ( "fmt" "strconv" ) type Element interface{} type List []Element type Person struct { name string age int } func (p Person) String() string { return "(name: " + p.name + " - age: " + strconv.Itoa(p.age) + " years)" } func main() { list := make(List, 3) list[0] = 1 // an int list[1] = "Hello" // a string list[2] = Person{"Dennis", 70} for index, element := range list { if value, ok := element.(int); ok { fmt.Printf("list[%d] is an int and its value is %d\n", index, value) } else if value, ok := element.(string); ok { fmt.Printf("list[%d] is a string and its value is %s\n", index, value) } else if value, ok := element.(Person); ok { fmt.Printf("list[%d] is a Person and its value is %s\n", index, value) } else { fmt.Println("list[%d] is of a different type", index) } } }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/fa/code/src/apps/ch.3.2/main.go
fa/code/src/apps/ch.3.2/main.go
// Example code for Chapter 3.2 from "Build Web Application with Golang" // Purpose: Shows how to acces the form values from the request package main import ( "fmt" "log" "net/http" "strings" ) func sayhelloName(w http.ResponseWriter, r *http.Request) { r.ParseForm() // parse arguments, you have to call this by yourself fmt.Println(r.Form) // print form information in server side fmt.Println("path", r.URL.Path) fmt.Println("scheme", r.URL.Scheme) fmt.Println(r.Form["url_long"]) for k, v := range r.Form { fmt.Println("key:", k) fmt.Println("val:", strings.Join(v, "")) } fmt.Fprintf(w, "Hello astaxie!") // send data to client side } func main() { http.HandleFunc("/", sayhelloName) // set router err := http.ListenAndServe(":9090", nil) // set listen port if err != nil { log.Fatal("ListenAndServe: ", err) } }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/fa/code/src/apps/ch.4.2/main.go
fa/code/src/apps/ch.4.2/main.go
// Example code for Chapter 4.2 from "Build Web Application with Golang" // Purpose: Shows how to perform server-side validation of user input from a form. // Also shows to use multiple template files with predefined template names. // Run `go run main.go` and then access http://localhost:9090 package main import ( "apps/ch.4.2/validator" "html/template" "log" "net/http" ) const ( PORT = "9090" HOST_URL = "http://localhost:" + PORT ) var t *template.Template type Links struct { BadLinks [][2]string } // invalid links to display for testing. var links Links func index(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, HOST_URL+"/profile", http.StatusTemporaryRedirect) } func profileHandler(w http.ResponseWriter, r *http.Request) { t.ExecuteTemplate(w, "profile", links) } func checkProfile(w http.ResponseWriter, r *http.Request) { r.ParseForm() p := validator.ProfilePage{&r.Form} t.ExecuteTemplate(w, "submission", p.GetErrors()) } // This function is called before main() func init() { // Note: we can reference the loaded templates by their defined name inside the template files. t = template.Must(template.ParseFiles("profile.gtpl", "submission.gtpl")) list := make([][2]string, 2) list[0] = [2]string{HOST_URL + "/checkprofile", "No data"} list[1] = [2]string{HOST_URL + "/checkprofile?age=1&gender=guy&shirtsize=big", "Invalid options"} links = Links{list} } func main() { http.HandleFunc("/", index) http.HandleFunc("/profile", profileHandler) http.HandleFunc("/checkprofile", checkProfile) err := http.ListenAndServe(":"+PORT, nil) // setting listening port if err != nil { log.Fatal("ListenAndServe: ", err) } }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/fa/code/src/apps/ch.4.2/validator/main.go
fa/code/src/apps/ch.4.2/validator/main.go
// This file contains all the validators to validate the profile page. package validator import ( "errors" "fmt" "net/url" "regexp" "strconv" "strings" "time" ) type ProfilePage struct { Form *url.Values } type Errors struct { Errors []error } // Goes through the form object and validates each element. // Attachs an error to the output if validation fails. func (p *ProfilePage) GetErrors() Errors { errs := make([]error, 0, 10) if *p.Form == nil || len(*p.Form) < 1 { errs = append(errs, errors.New("No data was received. Please submit from the profile page.")) } for name, val := range *p.Form { if fn, ok := stringValidator[name]; ok { if err := fn(strings.Join(val, "")); err != nil { errs = append(errs, err) } } else { if fn, ok := stringsValidator[name]; ok { if err := fn(val); err != nil { errs = append(errs, err) } } } } return Errors{errs} } const ( // Used for parsing the time mmddyyyyForm = "01/02/2006" // we want the date sent in this format yyyymmddForm = "2006-01-02" // However, HTML5 pages send the date in this format ) var stringValidator map[string]func(string) error = map[string]func(string) error{ // parameter name : validator reference "age": checkAge, "birthday": checkDate, "chineseName": checkChineseName, "email": checkEmail, "gender": checkGender, "shirtsize": checkShirtSize, "username": checkUsername, } var stringsValidator map[string]func([]string) error = map[string]func([]string) error{ // parameter name : validator reference "sibling": checkSibling, } // Returns true if slices have a common element func doSlicesIntersect(s1, s2 []string) bool { if s1 == nil || s2 == nil { return false } for _, str := range s1 { if isElementInSlice(str, s2) { return true } } return false } func isElementInSlice(str string, sl []string) bool { if sl == nil || str == "" { return false } for _, v := range sl { if v == str { return true } } return false } // Checks if all the characters are chinese characters. Won't check if empty.' func checkChineseName(str string) error { if str != "" { if m, _ := regexp.MatchString("^[\\x{4e00}-\\x{9fa5}]+$", strings.Trim(str, " ")); !m { return errors.New("Please make sure that the chinese name only contains chinese characters.") } } return nil } // Checks if a user name exist. func checkUsername(str string) error { if strings.Trim(str, " ") == "" { return errors.New("Please enter a username.") } return nil } // Check if age is a number and between 13 and 130 func checkAge(str string) error { age, err := strconv.Atoi(str) if str == "" || err != nil { return errors.New("Please enter a valid age.") } if age < 13 { return errors.New("You must be at least 13 years of age to submit.") } if age > 130 { return errors.New("You're too old to register, grandpa.") } return nil } func checkEmail(str string) error { if m, err := regexp.MatchString(`^[^@]+@[^@]+$`, str); !m { fmt.Println("err = ", err) return errors.New("Please enter a valid email address.") } return nil } // Checks if a valid date was passed. func checkDate(str string) error { _, err := time.Parse(mmddyyyyForm, str) if err != nil { _, err = time.Parse(yyyymmddForm, str) } if str == "" || err != nil { return errors.New("Please enter a valid Date.") } return nil } // Checks if the passed input is a known gender option func checkGender(str string) error { if str == "" { return nil } siblings := []string{"m", "f", "na"} if !isElementInSlice(str, siblings) { return errors.New("Please select a valid gender.") } return nil } // Check if all the values are known options. func checkSibling(strs []string) error { if strs == nil || len(strs) < 1 { return nil } siblings := []string{"m", "f"} if siblings != nil && !doSlicesIntersect(siblings, strs) { return errors.New("Please select a valid sibling") } return nil } // Checks if the shirt size is a known option. func checkShirtSize(str string) error { if str == "" { return nil } shirts := []string{"s", "m", "l", "xl", "xxl"} if !isElementInSlice(str, shirts) { return errors.New("Please select a valid shirt size") } return nil }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/fa/code/src/apps/ch.2.2/main.go
fa/code/src/apps/ch.2.2/main.go
// Example code for Chapter 2.2 from "Build Web Application with Golang" // Purpose: Goes over the assignment and manipulation of basic data types. package main import ( "errors" "fmt" ) // constants const Pi = 3.1415926 // booleans default to `false` var isActive bool // global variable var enabled, disabled = true, false // omit type of variables // grouped definitions const ( i = 1e4 MaxThread = 10 prefix = "astaxie_" ) var ( frenchHello string // basic form to define string emptyString string = "" // define a string with empty string ) func show_multiple_assignments() { fmt.Println("show_multiple_assignments()") var v1 int = 42 // Define three variables with type "int", and initialize their values. // vname1 is v1, vname2 is v2, vname3 is v3 var v2, v3 int = 2, 3 // `:=` only works in functions // `:=` is the short way of declaring variables without // specifying the type and using the keyboard `var`. vname1, vname2, vname3 := v1, v2, v3 // `_` disregards the returned value. _, b := 34, 35 fmt.Printf("vname1 = %v, vname2 = %v, vname3 = %v\n", vname1, vname2, vname3) fmt.Printf("v1 = %v, v2 = %v, v3 = %v\n", v1, v2, v3) fmt.Println("b =", b) } func show_bool() { fmt.Println("show_bool()") var available bool // local variable valid := false // Shorthand assignment available = true // assign value to variable fmt.Printf("valid = %v, !valid = %v\n", valid, !valid) fmt.Printf("available = %v\n", available) } func show_different_types() { fmt.Println("show_different_types()") var ( unicodeChar rune a int8 b int16 c int32 d int64 e byte f uint8 g int16 h uint32 i uint64 ) var cmplx complex64 = 5 + 5i fmt.Println("Default values for int types") fmt.Println(unicodeChar, a, b, c, d, e, f, g, h, i) fmt.Printf("Value is: %v\n", cmplx) } func show_strings() { fmt.Println("show_strings()") no, yes, maybe := "no", "yes", "maybe" // brief statement japaneseHello := "Ohaiyou" frenchHello = "Bonjour" // basic form of assign values fmt.Println("Random strings") fmt.Println(frenchHello, japaneseHello, no, yes, maybe) // The backtick, `, will not escape any character in a string fmt.Println(`This is on multiple lines`) } func show_string_manipulation() { fmt.Println("show_string_manipulation()") var s string = "hello" //You can't do this with strings //s[0] = 'c' s = "hello" c := []byte(s) // convert string to []byte type c[0] = 'c' s2 := string(c) // convert back to string type m := " world" a := s + m d := "c" + s[1:] // you cannot change string values by index, but you can get values instead. fmt.Printf("%s\n", d) fmt.Printf("s = %s, c = %v\n", s, c) fmt.Printf("s2 = %s\n", s2) fmt.Printf("combined strings\na = %s, d = %s\n", a, d) } func show_errors() { fmt.Println("show_errors()") err := errors.New("Example error message\n") if err != nil { fmt.Print(err) } } func show_iota() { fmt.Println("show_iota()") const ( x = iota // x == 0 y = iota // y == 1 z = iota // z == 2 w // If there is no expression after constants name, // it uses the last expression, so here is saying w = iota implicitly. // Therefore w == 3, and y and x both can omit "= iota" as well. ) const v = iota // once iota meets keyword `const`, it resets to `0`, so v = 0. const ( e, f, g = iota, iota, iota // e=0,f=0,g=0 values of iota are same in one line. ) fmt.Printf("x = %v, y = %v, z = %v, w = %v\n", x, y, z, w) fmt.Printf("v = %v\n", v) fmt.Printf("e = %v, f = %v, g = %v\n", e, f, g) } // Functions and variables starting with a capital letter are public to other packages. // Everything else is private. func This_is_public() {} func this_is_private() {} func set_default_values() { // default values for the types. const ( a int = 0 b int8 = 0 c int32 = 0 d int64 = 0 e uint = 0x0 f rune = 0 // the actual type of rune is int32 g byte = 0x0 // the actual type of byte is uint8 h float32 = 0 // length is 4 byte i float64 = 0 //length is 8 byte j bool = false k string = "" ) } func show_arrays() { fmt.Println("show_arrays()") var arr [10]int // an array of type int arr[0] = 42 // array is 0-based arr[1] = 13 // assign value to element a := [3]int{1, 2, 3} // define a int array with 3 elements b := [10]int{1, 2, 3} // define a int array with 10 elements, // and first three are assigned, rest of them use default value 0. c := [...]int{4, 5, 6} // use `…` replace with number of length, Go will calculate it for you. // define a two-dimensional array with 2 elements, and each element has 4 elements. doubleArray := [2][4]int{[4]int{1, 2, 3, 4}, [4]int{5, 6, 7, 8}} // You can write about declaration in a shorter way. easyArray := [2][4]int{{1, 2, 3, 4}, {5, 6, 7, 8}} fmt.Println("arr =", arr) fmt.Printf("The first element is %d\n", arr[0]) // get element value, it returns 42 fmt.Printf("The last element is %d\n", arr[9]) //it returns default value of 10th element in this array, which is 0 in this case. fmt.Println("array a =", a) fmt.Println("array b =", b) fmt.Println("array c =", c) fmt.Println("array doubleArray =", doubleArray) fmt.Println("array easyArray =", easyArray) } func show_slices() { fmt.Println("show_slices()") // define a slice with 10 elements which types are byte var ar = [10]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'} // define two slices with type []byte var a, b []byte // a points to elements from 3rd to 5th in array ar. a = ar[2:5] // now a has elements ar[2]、ar[3] and ar[4] // b is another slice of array ar b = ar[3:5] // now b has elements ar[3] and ar[4] // define an array var array = [10]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'} // define two slices var aSlice, bSlice []byte // some convenient operations aSlice = array[:3] // equals to aSlice = array[0:3] aSlice has elements a,b,c aSlice = array[5:] // equals to aSlice = array[5:10] aSlice has elements f,g,h,i,j aSlice = array[:] // equals to aSlice = array[0:10] aSlice has all elements // slice from slice aSlice = array[3:7] // aSlice has elements d,e,f,g,len=4,cap=7 bSlice = aSlice[1:3] // bSlice contains aSlice[1], aSlice[2], so it has elements e,f bSlice = aSlice[:3] // bSlice contains aSlice[0], aSlice[1], aSlice[2], so it has d,e,f bSlice = aSlice[0:5] // slcie could be expanded in range of cap, now bSlice contains d,e,f,g,h bSlice = aSlice[:] // bSlice has same elements as aSlice does, which are d,e,f,g fmt.Println("slice ar =", ar) fmt.Println("slice a =", a) fmt.Println("slice b =", b) fmt.Println("array =", array) fmt.Println("slice aSlice =", aSlice) fmt.Println("slice bSlice =", bSlice) fmt.Println("len(bSlice) =", len(bSlice)) } func show_map() { fmt.Println("show_map()") // use string as key type, int as value type, and you have to use `make` initialize it. var numbers map[string]int // another way to define map numbers = make(map[string]int) numbers["one"] = 1 // assign value by key numbers["ten"] = 10 numbers["three"] = 3 // Initialize a map rating := map[string]float32{"C": 5, "Go": 4.5, "Python": 4.5, "C++": 2} fmt.Println("map numbers =", numbers) fmt.Println("The third number is: ", numbers["three"]) // get values // It prints: The third number is: 3 // map has two return values. For second value, if the key doesn't exist,ok is false,true otherwise. csharpRating, ok := rating["C#"] if ok { fmt.Println("C# is in the map and its rating is ", csharpRating) } else { fmt.Println("We have no rating associated with C# in the map") } delete(rating, "C") // delete element with key "c" fmt.Printf("map rating = %#v\n", rating) } func main() { show_multiple_assignments() show_bool() show_different_types() show_strings() show_string_manipulation() show_errors() show_iota() set_default_values() show_arrays() show_slices() show_map() }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/fa/code/src/apps/ch.2.2/what_is_wrong_with_this/main.go
fa/code/src/apps/ch.2.2/what_is_wrong_with_this/main.go
// Example code for Chapter 2.2 from "Build Web Application with Golang" // Purpose: Try to fix this program. // From the console, type `go run main.go` package main func main() { var i int }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/fa/code/src/apps/ch.2.4/main.go
fa/code/src/apps/ch.2.4/main.go
// Example code for Chapter 2.4 from "Build Web Application with Golang" // Purpose: Shows different ways of creating a struct package main import "fmt" func show_basic_struct() { fmt.Println("\nshow_basic_struct()") type person struct { name string age int } var P person // p is person type P.name = "Astaxie" // assign "Astaxie" to the filed 'name' of p P.age = 25 // assign 25 to field 'age' of p fmt.Printf("The person's name is %s\n", P.name) // access field 'name' of p tom := person{"Tom", 25} bob := person{age: 24, name: "Bob"} fmt.Printf("tom = %+v\n", tom) fmt.Printf("bob = %#v\n", bob) } func show_anonymous_struct() { fmt.Println("\nshow_anonymous_struct()") fmt.Printf("Anonymous struct = %#v\n", struct { name string count int }{ "counter", 1, }) } func main() { show_basic_struct() show_anonymous_struct() }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/fa/code/src/apps/ch.2.4/embedded_structs_with_name_conflict/main.go
fa/code/src/apps/ch.2.4/embedded_structs_with_name_conflict/main.go
// Example code for Chapter 2.4 from "Build Web Application with Golang" // Purpose: Shows a name conflict with a embedded field package main import "fmt" type Human struct { name string age int phone string // Human has phone field } type Employee struct { Human // embedded field Human speciality string phone string // phone in employee } func main() { Bob := Employee{Human{"Bob", 34, "777-444-XXXX"}, "Designer", "333-222"} fmt.Println("Bob's work phone is:", Bob.phone) // access phone field in Human fmt.Println("Bob's personal phone is:", Bob.Human.phone) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/fa/code/src/apps/ch.2.4/embedded_structs/main.go
fa/code/src/apps/ch.2.4/embedded_structs/main.go
// Example code for Chapter 2.4 from "Build Web Application with Golang" // Purpose: Example of embedded fields package main import "fmt" type Human struct { name string age int weight int } type Student struct { Human // anonymous field, it means Student struct includes all fields that Human has. speciality string } func main() { // initialize a student mark := Student{Human{"Mark", 25, 120}, "Computer Science"} // access fields fmt.Println("His name is ", mark.name) fmt.Println("His age is ", mark.age) fmt.Println("His weight is ", mark.weight) fmt.Println("His speciality is ", mark.speciality) // modify notes mark.speciality = "AI" fmt.Println("Mark changed his speciality") fmt.Println("His speciality is ", mark.speciality) // modify age fmt.Println("Mark become old") mark.age = 46 fmt.Println("His age is", mark.age) // modify weight fmt.Println("Mark is not an athlete any more") mark.weight += 60 fmt.Println("His weight is", mark.weight) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/fa/code/src/apps/ch.2.4/compare_age/main.go
fa/code/src/apps/ch.2.4/compare_age/main.go
// Example code for Chapter 2.4 from "Build Web Application with Golang" // Purpose: Shows you how to pass and use structs. package main import "fmt" // define a new type type person struct { name string age int } // compare age of two people, return the older person and differences of age // struct is passed by value func Older(p1, p2 person) (person, int) { if p1.age > p2.age { return p1, p1.age - p2.age } return p2, p2.age - p1.age } func main() { var tom person // initialization tom.name, tom.age = "Tom", 18 // initialize two values by format "field:value" bob := person{age: 25, name: "Bob"} // initialize two values with order paul := person{"Paul", 43} tb_Older, tb_diff := Older(tom, bob) tp_Older, tp_diff := Older(tom, paul) bp_Older, bp_diff := Older(bob, paul) fmt.Printf("Of %s and %s, %s is older by %d years\n", tom.name, bob.name, tb_Older.name, tb_diff) fmt.Printf("Of %s and %s, %s is older by %d years\n", tom.name, paul.name, tp_Older.name, tp_diff) fmt.Printf("Of %s and %s, %s is older by %d years\n", bob.name, paul.name, bp_Older.name, bp_diff) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/fa/code/src/apps/ch.2.4/embedded_structs2/main.go
fa/code/src/apps/ch.2.4/embedded_structs2/main.go
// Example code for Chapter 2.4 from "Build Web Application with Golang" // Purpose: Another example of embedded fields package main import "fmt" type Skills []string type Human struct { name string age int weight int } type Student struct { Human // struct as embedded field Skills // string slice as embedded field int // built-in type as embedded field speciality string } func main() { // initialize Student Jane jane := Student{Human: Human{"Jane", 35, 100}, speciality: "Biology"} // access fields fmt.Println("Her name is ", jane.name) fmt.Println("Her age is ", jane.age) fmt.Println("Her weight is ", jane.weight) fmt.Println("Her speciality is ", jane.speciality) // modify value of skill field jane.Skills = []string{"anatomy"} fmt.Println("Her skills are ", jane.Skills) fmt.Println("She acquired two new ones ") jane.Skills = append(jane.Skills, "physics", "golang") fmt.Println("Her skills now are ", jane.Skills) // modify embedded field jane.int = 3 fmt.Println("Her preferred number is", jane.int) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/fa/code/src/mymath/sqrt.go
fa/code/src/mymath/sqrt.go
// Example code for Chapter 1.2 from "Build Web Application with Golang" // Purpose: Shows how to create a simple package called `mymath` // This package must be imported from another go file to run. package mymath func Sqrt(x float64) float64 { z := 0.0 for i := 0; i < 1000; i++ { z -= (z*z - x) / (2 * x) } return z }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/zh-tw/a_herf.go
zh-tw/a_herf.go
package main import( "fmt" "log" "os" "path/filepath" "sort" ) func dir()([]string,error) { path, err := os.Getwd() if err != nil { fmt.Println("err is:", err) } log.Println(path) path =path +"/*.html" fmt.Println(path) files,err := filepath.Glob(path) var s =make([]string,len(files)) var head uint8 =0 for _,k :=range files { filename := filepath.Base(k) head=filename[0] if (head < 52) { s = append(s, filename) fmt.Println(filename) } } sort.Strings(s) return s,err } func htmlfile(filename string,next_path string,last_path string)(error){ file,err:= os.OpenFile("./"+filename,os.O_RDWR,0666) if err !=nil{ fmt.Println("something is err :",err) } defer file.Close() var add_string1 string = "\n<a href=\"./"+next_path+"\">下一页</a>\n" var add_string2 string = "\n<a href=\"./"+last_path+"\">下一页</a>\n" file.Seek(1,2) _,err=file.WriteString(add_string1) if(err!=nil){ fmt.Println("err:",err) } _,err=file.WriteString(add_string2) file.Seek(0,0) if(err!=nil){ fmt.Println("err:",err) } var f =make([]byte,50000) _,err=file.Read(f) if(err!=nil){ fmt.Println("error:",err) } //fmt.Println(string(f)) return err } func nextandlast(filenames []string,index int )(filename string,next_path string,last_path string){ fmt.Println(index," ---",index+1) filename = filenames[index] if(0<index && index<len(filenames)-1) { next_path = filenames[index+1] last_path = filenames[index-1] }else if(index==0){ next_path =filenames[index+1] last_path = filenames[len(filenames)-1] }else if(index==len(filenames)){ next_path =filenames[0] last_path =filenames[index-1] }else{ return } return filename,next_path,last_path } func main(){ files,err:=dir() if(err!=nil){ fmt.Println(err) } //fmt.Println(files) // var tmp string ="\0" for i, v :=range files{ if(v!=""){ fmt.Println(v) filename,next_path,last_path :=nextandlast(files,i) err:=htmlfile(filename,next_path,last_path) if(err!=nil){ fmt.Println("err=",err) }else if(v==""){ continue } } } log.Println("end") return }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/zh-tw/build.go
zh-tw/build.go
package main import ( "bufio" "fmt" "github.com/a8m/mark" "io/ioutil" "os" "path/filepath" "regexp" "strings" ) // 定义一个访问者结构体 type Visitor struct{} func (self *Visitor) md2html(arg map[string]string) error { from := arg["from"] to := arg["to"] s := `<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> ` err := filepath.Walk(from+"/", func(path string, f os.FileInfo, err error) error { if f == nil { return err } if f.IsDir() { return nil } if (f.Mode() & os.ModeSymlink) > 0 { return nil } if !strings.HasSuffix(f.Name(), ".md") { return nil } file, err := os.Open(path) if err != nil { return err } input_byte, _ := ioutil.ReadAll(file) input := string(input_byte) input = regexp.MustCompile(`\[(.*?)\]\(<?(.*?)\.md>?\)`).ReplaceAllString(input, "[$1](<$2.html>)") if f.Name() == "README.md" { input = regexp.MustCompile(`https:\/\/github\.com\/astaxie\/build-web-application-with-golang\/blob\/master\/`).ReplaceAllString(input, "") } // 以#开头的行,在#后增加空格 // 以#开头的行, 删除多余的空格 input = FixHeader(input) // 删除页面链接 input = RemoveFooterLink(input) // remove image suffix input = RemoveImageLinkSuffix(input) var out *os.File filename := strings.Replace(f.Name(), ".md", ".html", -1) fmt.Println(to + "/" + filename) if out, err = os.Create(to + "/" + filename); err != nil { fmt.Fprintf(os.Stderr, "Error creating %s: %v", f.Name(), err) os.Exit(-1) } defer out.Close() opts := mark.DefaultOptions() opts.Smartypants = true opts.Fractions = true // r1 := []rune(s1) m := mark.New(input, opts) w := bufio.NewWriter(out) n4, err := w.WriteString(s + m.Render()) fmt.Printf("wrote %d bytes\n", n4) w.Flush() if err != nil { fmt.Fprintln(os.Stderr, "Parsing Error", err) os.Exit(-1) } return nil }) return err } func FixHeader(input string) string { re_header := regexp.MustCompile(`(?m)^#.+$`) re_sub := regexp.MustCompile(`^(#+)\s*(.+)$`) fixer := func(header string) string { s := re_sub.FindStringSubmatch(header) return s[1] + " " + s[2] } return re_header.ReplaceAllStringFunc(input, fixer) } func RemoveFooterLink(input string) string { re_footer := regexp.MustCompile(`(?m)^#{2,} links.*?\n(.+\n)*`) return re_footer.ReplaceAllString(input, "") } func RemoveImageLinkSuffix(input string) string { re_footer := regexp.MustCompile(`png\?raw=true`) return re_footer.ReplaceAllString(input, "png") } func main() { tmp := os.Getenv("TMP") if tmp == "" { tmp = "." } workdir := os.Getenv("WORKDIR") if workdir == "" { workdir = "." } arg := map[string]string{ "from": workdir, "to": tmp, } v := &Visitor{} err := v.md2html(arg) if err != nil { fmt.Printf("filepath.Walk() returned %v\n", err) } }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/zh-tw/build_new.go
zh-tw/build_new.go
package main import ( "fmt" "io/ioutil" "bufio" "net/http" "os" "path/filepath" "regexp" "strings" ) // 开发者 GitHub token const token = "" // 定义一个访问者结构体 type Visitor struct{} func (self *Visitor) md2html(arg map[string]string) error { from := arg["from"] to := arg["to"] s := `<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> ` err := filepath.Walk(from+"/", func(path string, f os.FileInfo, err error) error { if f == nil { return err } if f.IsDir() { return nil } if (f.Mode() & os.ModeSymlink) > 0 { return nil } if !strings.HasSuffix(f.Name(), ".md") { return nil } file, err := os.Open(path) if err != nil { return err } input_byte, _ := ioutil.ReadAll(file) input := string(input_byte) input = regexp.MustCompile(`\[(.*?)\]\(<?(.*?)\.md>?\)`).ReplaceAllString(input, "[$1](<$2.html>)") if f.Name() == "README.md" { input = regexp.MustCompile(`https:\/\/github\.com\/astaxie\/build-web-application-with-golang\/blob\/master\/`).ReplaceAllString(input, "") } // 以#开头的行,在#后增加空格 // 以#开头的行, 删除多余的空格 input = FixHeader(input) // 删除页面链接 input = RemoveFooterLink(input) // remove image suffix input = RemoveImageLinkSuffix(input) var out *os.File filename := strings.Replace(f.Name(), ".md", ".html", -1) fmt.Println(to + "/" + filename) if out, err = os.Create(to + "/" + filename); err != nil { fmt.Fprintf(os.Stderr, "Error creating %s: %v", f.Name(), err) os.Exit(-1) } defer out.Close() client := &http.Client{} req, err := http.NewRequest("POST", "https://api.github.com/markdown/raw", strings.NewReader(input)) if err != nil { // handle error } req.Header.Set("Content-Type", "text/plain") req.Header.Set("charset", "utf-8") req.Header.Set("Authorization", "token "+token) // resp, err := client.Do(req) if err != nil { fmt.Println("err:",err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } w := bufio.NewWriter(out) n4, err := w.WriteString(s + string(body)) //m.Render() fmt.Printf("wrote %d bytes\n", n4) // fmt.Printf("wrote %d bytes\n", n4) //使用 Flush 来确保所有缓存的操作已写入底层写入器。 w.Flush() if err != nil { fmt.Fprintln(os.Stderr, "Parsing Error", err) os.Exit(-1) } return nil }) return err } func FixHeader(input string) string { re_header := regexp.MustCompile(`(?m)^#.+$`) re_sub := regexp.MustCompile(`^(#+)\s*(.+)$`) fixer := func(header string) string { s := re_sub.FindStringSubmatch(header) return s[1] + " " + s[2] } return re_header.ReplaceAllStringFunc(input, fixer) } func RemoveFooterLink(input string) string { re_footer := regexp.MustCompile(`(?m)^#{2,} links.*?\n(.+\n)*`) return re_footer.ReplaceAllString(input, "") } func RemoveImageLinkSuffix(input string) string { re_footer := regexp.MustCompile(`png\?raw=true`) return re_footer.ReplaceAllString(input, "png") } func main() { tmp := os.Getenv("TMP") if tmp == "" { tmp = "." } workdir := os.Getenv("WORKDIR") if workdir == "" { workdir = "." } arg := map[string]string{ "from": workdir, "to": tmp, } v := &Visitor{} err := v.md2html(arg) if err != nil { fmt.Printf("filepath.Walk() returned %v\n", err) } }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/zh-tw/src/1.2/sqrt.go
zh-tw/src/1.2/sqrt.go
// 章節 1.2 // $GOPATH/src/mymath/sqrt.go package mymath func Sqrt(x float64) float64 { z := 0.0 for i := 0; i < 1000; i++ { z -= (z*z - x) / (2 * x) } return z }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/zh-tw/src/1.2/main.go
zh-tw/src/1.2/main.go
// 章節 1.2 // $GOPATH/src/mathapp/main.go package main import ( "fmt" "mymath" ) func main() { fmt.Printf("Hello, world. Sqrt(2) = %v\n", mymath.Sqrt(2)) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/es/code/src/apps/ch.1.2/main.go
es/code/src/apps/ch.1.2/main.go
// Código de ejemplo para el capítulo 1.2 del libro "Construye Aplicaciones Web con Golang" // Propósito: Ejecuta este archivo para verificar que tu espacio de trabajo está configurado correctamente. // Para ejecutarlo, busca el directorio actual en la terminal y escribe `go run main.go` // Si el texto "Hello World" no se muestra, entonces configura tu ambiente de trabajo nuevamente. package main import ( "fmt" "mymath" ) func main() { fmt.Printf("Hello, world. Sqrt(2) = %v\n", mymath.Sqrt(2)) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/es/code/src/mymath/sqrt.go
es/code/src/mymath/sqrt.go
// Código de ejmplo para el capítulo 1.2 de "Construye Aplicaciones Web con Golang" // Propósito: Muestra como crear un paquete simple llamado `mymath` // Este paquete debe ser importado desde otro archivo Go para poder ejecutarse. package mymath func Sqrt(x float64) float64 { z := 0.0 for i := 0; i < 1000; i++ { z -= (z*z - x) / (2 * x) } return z }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.5.4/main.go
pt-br/code/src/apps/ch.5.4/main.go
// Example code for Chapter 5.4 from "Build Web Application with Golang" // Purpose: Show how to perform CRUD operations using a postgres driver package main import ( "database/sql" "fmt" "time" _ "github.com/lib/pq" ) const ( DB_USER = "user" DB_PASSWORD = "" DB_NAME = "test" ) func main() { dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable", DB_USER, DB_PASSWORD, DB_NAME) db, err := sql.Open("postgres", dbinfo) checkErr(err) defer db.Close() fmt.Println("# Inserting values") var lastInsertId int err = db.QueryRow("INSERT INTO userinfo(username,departname,created) VALUES($1,$2,$3) returning uid;", "astaxie", "software developement", "2012-12-09").Scan(&lastInsertId) checkErr(err) fmt.Println("id of last inserted row =", lastInsertId) fmt.Println("# Updating") stmt, err := db.Prepare("update userinfo set username=$1 where uid=$2") checkErr(err) res, err := stmt.Exec("astaxieupdate", lastInsertId) checkErr(err) affect, err := res.RowsAffected() checkErr(err) fmt.Println(affect, "row(s) changed") fmt.Println("# Querying") rows, err := db.Query("SELECT * FROM userinfo") checkErr(err) for rows.Next() { var uid int var username string var department string var created time.Time err = rows.Scan(&uid, &username, &department, &created) checkErr(err) fmt.Println("uid | username | department | created ") fmt.Printf("%3v | %8v | %6v | %6v\n", uid, username, department, created) } fmt.Println("# Deleting") stmt, err = db.Prepare("delete from userinfo where uid=$1") checkErr(err) res, err = stmt.Exec(lastInsertId) checkErr(err) affect, err = res.RowsAffected() checkErr(err) fmt.Println(affect, "row(s) changed") } func checkErr(err error) { if err != nil { panic(err) } }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.4.1/main.go
pt-br/code/src/apps/ch.4.1/main.go
// Example code for Chapter 4.1 from "Build Web Application with Golang" // Purpose: Shows how to create a simple login using a template // Run: `go run main.go`, then access `http://localhost:9090` and `http://localhost:9090/login` package main import ( "fmt" "html/template" "log" "net/http" "strings" ) func sayhelloName(w http.ResponseWriter, r *http.Request) { r.ParseForm() //Parse url parameters passed, then parse the response packet for the POST body (request body) // attention: If you do not call ParseForm method, the following data can not be obtained form fmt.Println(r.Form) // print information on server side. fmt.Println("path", r.URL.Path) fmt.Println("scheme", r.URL.Scheme) fmt.Println(r.Form["url_long"]) for k, v := range r.Form { fmt.Println("key:", k) fmt.Println("val:", strings.Join(v, "")) } fmt.Fprintf(w, "Hello astaxie!") // write data to response } func login(w http.ResponseWriter, r *http.Request) { fmt.Println("method:", r.Method) //get request method if r.Method == "GET" { t, _ := template.ParseFiles("login.gtpl") t.Execute(w, nil) } else { r.ParseForm() // logic part of log in fmt.Println("username:", r.Form["username"]) fmt.Println("password:", r.Form["password"]) } } func main() { http.HandleFunc("/", sayhelloName) // setting router rule http.HandleFunc("/login", login) err := http.ListenAndServe(":9090", nil) // setting listening port if err != nil { log.Fatal("ListenAndServe: ", err) } }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.5.5/main.go
pt-br/code/src/apps/ch.5.5/main.go
// Example code for Chapter 5.5 // Purpose is to show to use BeeDB ORM for basic CRUD operations for sqlite3 package main import ( "database/sql" "fmt" "github.com/astaxie/beedb" _ "github.com/mattn/go-sqlite3" "time" ) var orm beedb.Model type Userinfo struct { Uid int `beedb:"PK"` Username string Department string Created string } const DB_PATH = "./foo.db" func checkError(err error) { if err != nil { panic(err) } } func getTimeStamp() string { return time.Now().Format("2006-01-02 15:04:05") } func insertUsingStruct() int64 { fmt.Println("insertUsingStruct()") var obj Userinfo obj.Username = "Test Add User" obj.Department = "Test Add Department" obj.Created = getTimeStamp() checkError(orm.Save(&obj)) fmt.Printf("%+v\n", obj) return int64(obj.Uid) } func insertUsingMap() int64 { fmt.Println("insertUsingMap()") add := make(map[string]interface{}) add["username"] = "astaxie" add["department"] = "cloud develop" add["created"] = getTimeStamp() id, err := orm.SetTable("userinfo").Insert(add) checkError(err) fmt.Println("Last row inserted id =", id) return id } func getOneUserInfo(id int64) Userinfo { fmt.Println("getOneUserInfo()") var obj Userinfo checkError(orm.Where("uid=?", id).Find(&obj)) return obj } func getAllUserInfo(id int64) []Userinfo { fmt.Println("getAllUserInfo()") var alluser []Userinfo checkError(orm.Limit(10).Where("uid>?", id).FindAll(&alluser)) return alluser } func updateUserinfo(id int64) { fmt.Println("updateUserinfo()") var obj Userinfo obj.Uid = int(id) obj.Username = "Update Username" obj.Department = "Update Department" obj.Created = getTimeStamp() checkError(orm.Save(&obj)) fmt.Printf("%+v\n", obj) } func updateUsingMap(id int64) { fmt.Println("updateUsingMap()") t := make(map[string]interface{}) t["username"] = "updateastaxie" //update one // id, err := orm.SetTable("userinfo").SetPK("uid").Where(2).Update(t) //update batch lastId, err := orm.SetTable("userinfo").Where("uid>?", id).Update(t) checkError(err) fmt.Println("Last row updated id =", lastId) } func getMapsFromSelect(id int64) []map[string][]byte { fmt.Println("getMapsFromSelect()") //Original SQL Backinfo resultsSlice []map[string][]byte //default PrimaryKey id c, err := orm.SetTable("userinfo").SetPK("uid").Where(id).Select("uid,username").FindMap() checkError(err) fmt.Printf("%+v\n", c) return c } func groupby() { fmt.Println("groupby()") //Original SQL Group By b, err := orm.SetTable("userinfo").GroupBy("username").Having("username='updateastaxie'").FindMap() checkError(err) fmt.Printf("%+v\n", b) } func joinTables(id int64) { fmt.Println("joinTables()") //Original SQL Join Table a, err := orm.SetTable("userinfo").Join("LEFT", "userdetail", "userinfo.uid=userdetail.uid").Where("userinfo.uid=?", id).Select("userinfo.uid,userinfo.username,userdetail.profile").FindMap() checkError(err) fmt.Printf("%+v\n", a) } func deleteWithUserinfo(id int64) { fmt.Println("deleteWithUserinfo()") obj := getOneUserInfo(id) id, err := orm.Delete(&obj) checkError(err) fmt.Println("Last row deleted id =", id) } func deleteRows() { fmt.Println("deleteRows()") //original SQL delete id, err := orm.SetTable("userinfo").Where("uid>?", 2).DeleteRow() checkError(err) fmt.Println("Last row updated id =", id) } func deleteAllUserinfo(id int64) { fmt.Println("deleteAllUserinfo()") //delete all data alluser := getAllUserInfo(id) id, err := orm.DeleteAll(&alluser) checkError(err) fmt.Println("Last row updated id =", id) } func main() { db, err := sql.Open("sqlite3", DB_PATH) checkError(err) orm = beedb.New(db) var lastIdInserted int64 fmt.Println("Inserting") lastIdInserted = insertUsingStruct() insertUsingMap() a := getOneUserInfo(lastIdInserted) fmt.Println(a) b := getAllUserInfo(lastIdInserted) fmt.Println(b) fmt.Println("Updating") updateUserinfo(lastIdInserted) updateUsingMap(lastIdInserted) fmt.Println("Querying") getMapsFromSelect(lastIdInserted) groupby() joinTables(lastIdInserted) fmt.Println("Deleting") deleteWithUserinfo(lastIdInserted) deleteRows() deleteAllUserinfo(lastIdInserted) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.1/main.go
pt-br/code/src/apps/ch.2.1/main.go
// Código de exemplo para o Capítulo 2.1 do "Build Web Application with Golang" // Propósito: Exemplo de Hello world demonstrando suporte para UTF-8. // Para executar, navegue até o diretório onde ele estiver salvo e digite no console `go run main.go` // Se você receber quadrados ou pontos de interrogação, possivelemente você não tenha as fontes instaladas. package main import "fmt" func main() { fmt.Printf("Hello, world or 你好,世界 or καλημ ́ρα κóσμ or こんにちは世界\n") }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.4.5/main.go
pt-br/code/src/apps/ch.4.5/main.go
// Example code for Chapter 4.5 // Purpose is to create a server to handle uploading files. package main import ( "apps/ch.4.4/nonce" "apps/ch.4.4/validator" "fmt" "html/template" "io" "mime/multipart" "net/http" "os" ) const MiB_UNIT = 1 << 20 var t *template.Template var submissions nonce.Nonces = nonce.New() func checkError(err error) { if err != nil { panic(err) } } func indexHandler(w http.ResponseWriter, r *http.Request) { err := t.ExecuteTemplate(w, "index", submissions.NewToken()) checkError(err) } func uploadHandler(w http.ResponseWriter, r *http.Request) { var errs validator.Errors r.ParseMultipartForm(32 * MiB_UNIT) token := r.Form.Get("token") if err := submissions.CheckThenMarkToken(token); err != nil { errs = validator.Errors{[]error{err}} } else { file, handler, err := r.FormFile("uploadfile") checkError(err) saveUpload(file, handler) } err := t.ExecuteTemplate(w, "upload", errs) checkError(err) } func saveUpload(file multipart.File, handler *multipart.FileHeader) { defer file.Close() fmt.Printf("Uploaded file info: %#v", handler.Header) localFilename := fmt.Sprintf("./uploads/%v.%v", handler.Filename, submissions.NewToken()) f, err := os.OpenFile(localFilename, os.O_WRONLY|os.O_CREATE, 0666) checkError(err) defer f.Close() _, err = io.Copy(f, file) checkError(err) } func init() { var err error t, err = template.ParseFiles("index.gtpl", "upload.gtpl") checkError(err) } func main() { http.HandleFunc("/", indexHandler) http.HandleFunc("/upload", uploadHandler) err := http.ListenAndServe(":9090", nil) checkError(err) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.4.5/nonce/main.go
pt-br/code/src/apps/ch.4.5/nonce/main.go
// A nonce is a number or string used only once. // This is useful for generating a unique token for login pages to prevent duplicate submissions. package nonce import ( "crypto/md5" "errors" "fmt" "io" "math/rand" "strconv" "time" ) // Contains a unique token type Nonce struct { Token string } // Keeps track of marked/used tokens type Nonces struct { hashs map[string]bool } func New() Nonces { return Nonces{make(map[string]bool)} } func (n *Nonces) NewNonce() Nonce { return Nonce{n.NewToken()} } // Returns a new unique token func (n *Nonces) NewToken() string { t := createToken() for n.HasToken(t) { t = createToken() } return t } // Checks if token has been marked. func (n *Nonces) HasToken(token string) bool { return n.hashs[token] == true } func (n *Nonces) MarkToken(token string) { n.hashs[token] = true } func (n *Nonces) CheckToken(token string) error { if token == "" { return errors.New("No token supplied") } if n.HasToken(token) { return errors.New("Duplicate submission.") } return nil } func (n *Nonces) CheckThenMarkToken(token string) error { defer n.MarkToken(token) if err := n.CheckToken(token); err != nil { return err } return nil } func createToken() string { h := md5.New() now := time.Now().Unix() io.WriteString(h, strconv.FormatInt(now, 10)) io.WriteString(h, strconv.FormatInt(rand.Int63(), 10)) return fmt.Sprintf("%x", h.Sum(nil)) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.4.5/validator/main.go
pt-br/code/src/apps/ch.4.5/validator/main.go
// This file contains all the validators to validate the profile page. package validator import ( "errors" "fmt" "net/url" "regexp" "strconv" "strings" "time" ) type ProfilePage struct { Form *url.Values } type Errors struct { Errors []error } // Goes through the form object and validates each element. // Attachs an error to the output if validation fails. func (p *ProfilePage) GetErrors() Errors { errs := make([]error, 0, 10) if *p.Form == nil || len(*p.Form) < 1 { errs = append(errs, errors.New("No data was received. Please submit from the profile page.")) } for name, val := range *p.Form { if fn, ok := stringValidator[name]; ok { if err := fn(strings.Join(val, "")); err != nil { errs = append(errs, err) } } else { if fn, ok := stringsValidator[name]; ok { if err := fn(val); err != nil { errs = append(errs, err) } } } } return Errors{errs} } const ( // Used for parsing the time mmddyyyyForm = "01/02/2006" // we want the date sent in this format yyyymmddForm = "2006-01-02" // However, HTML5 pages send the date in this format ) var stringValidator map[string]func(string) error = map[string]func(string) error{ // parameter name : validator reference "age": checkAge, "birthday": checkDate, "chineseName": checkChineseName, "email": checkEmail, "gender": checkGender, "shirtsize": checkShirtSize, "username": checkUsername, } var stringsValidator map[string]func([]string) error = map[string]func([]string) error{ // parameter name : validator reference "sibling": checkSibling, } // Returns true if slices have a common element func doSlicesIntersect(s1, s2 []string) bool { if s1 == nil || s2 == nil { return false } for _, str := range s1 { if isElementInSlice(str, s2) { return true } } return false } func isElementInSlice(str string, sl []string) bool { if sl == nil || str == "" { return false } for _, v := range sl { if v == str { return true } } return false } // Checks if all the characters are chinese characters. Won't check if empty.' func checkChineseName(str string) error { if str != "" { if m, _ := regexp.MatchString("^[\\x{4e00}-\\x{9fa5}]+$", strings.Trim(str, " ")); !m { return errors.New("Please make sure that the chinese name only contains chinese characters.") } } return nil } // Checks if a user name exist. func checkUsername(str string) error { if strings.Trim(str, " ") == "" { return errors.New("Please enter a username.") } return nil } // Check if age is a number and between 13 and 130 func checkAge(str string) error { age, err := strconv.Atoi(str) if str == "" || err != nil { return errors.New("Please enter a valid age.") } if age < 13 { return errors.New("You must be at least 13 years of age to submit.") } if age > 130 { return errors.New("You're too old to register, grandpa.") } return nil } func checkEmail(str string) error { if m, err := regexp.MatchString(`^[^@]+@[^@]+$`, str); !m { fmt.Println("err = ", err) return errors.New("Please enter a valid email address.") } return nil } // Checks if a valid date was passed. func checkDate(str string) error { _, err := time.Parse(mmddyyyyForm, str) if err != nil { _, err = time.Parse(yyyymmddForm, str) } if str == "" || err != nil { return errors.New("Please enter a valid Date.") } return nil } // Checks if the passed input is a known gender option func checkGender(str string) error { if str == "" { return nil } siblings := []string{"m", "f", "na"} if !isElementInSlice(str, siblings) { return errors.New("Please select a valid gender.") } return nil } // Check if all the values are known options. func checkSibling(strs []string) error { if strs == nil || len(strs) < 1 { return nil } siblings := []string{"m", "f"} if siblings != nil && !doSlicesIntersect(siblings, strs) { return errors.New("Please select a valid sibling") } return nil } // Checks if the shirt size is a known option. func checkShirtSize(str string) error { if str == "" { return nil } shirts := []string{"s", "m", "l", "xl", "xxl"} if !isElementInSlice(str, shirts) { return errors.New("Please select a valid shirt size") } return nil }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.4.5/client_upload/main.go
pt-br/code/src/apps/ch.4.5/client_upload/main.go
package main import ( "bytes" "fmt" "io" "io/ioutil" "mime/multipart" "net/http" "os" ) func checkError(err error) { if err != nil { panic(err) } } func postFile(filename string, targetUrl string) { bodyBuf := &bytes.Buffer{} bodyWriter := multipart.NewWriter(bodyBuf) fileWriter, err := bodyWriter.CreateFormFile("uploadfile", filename) checkError(err) fh, err := os.Open(filename) checkError(err) _, err = io.Copy(fileWriter, fh) checkError(err) contentType := bodyWriter.FormDataContentType() bodyWriter.Close() resp, err := http.Post(targetUrl, contentType, bodyBuf) checkError(err) defer resp.Body.Close() resp_body, err := ioutil.ReadAll(resp.Body) checkError(err) fmt.Println(resp.Status) fmt.Println(string(resp_body)) } func main() { target_url := "http://localhost:9090/upload" filename := "../file.txt" postFile(filename, target_url) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.5.3/main.go
pt-br/code/src/apps/ch.5.3/main.go
// Example code for Chapter 5.3 from "Build Web Application with Golang" // Purpose: Shows how to run simple CRUD operations using a sqlite driver package main import ( "database/sql" "fmt" _ "github.com/mattn/go-sqlite3" "time" ) const DB_PATH = "./foo.db" func main() { db, err := sql.Open("sqlite3", DB_PATH) checkErr(err) defer db.Close() fmt.Println("Inserting") stmt, err := db.Prepare("INSERT INTO userinfo(username, department, created) values(?,?,?)") checkErr(err) res, err := stmt.Exec("astaxie", "software developement", time.Now().Format("2006-01-02")) checkErr(err) id, err := res.LastInsertId() checkErr(err) fmt.Println("id of last inserted row =", id) fmt.Println("Updating") stmt, err = db.Prepare("update userinfo set username=? where uid=?") checkErr(err) res, err = stmt.Exec("astaxieupdate", id) checkErr(err) affect, err := res.RowsAffected() checkErr(err) fmt.Println(affect, "row(s) changed") fmt.Println("Querying") rows, err := db.Query("SELECT * FROM userinfo") checkErr(err) for rows.Next() { var uid int var username, department, created string err = rows.Scan(&uid, &username, &department, &created) checkErr(err) fmt.Println("uid | username | department | created") fmt.Printf("%3v | %6v | %8v | %6v\n", uid, username, department, created) } fmt.Println("Deleting") stmt, err = db.Prepare("delete from userinfo where uid=?") checkErr(err) res, err = stmt.Exec(id) checkErr(err) affect, err = res.RowsAffected() checkErr(err) fmt.Println(affect, "row(s) changed") } func checkErr(err error) { if err != nil { panic(err) } }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.4.4/main.go
pt-br/code/src/apps/ch.4.4/main.go
// Example code for Chapter 3.2 from "Build Web Application with Golang" // Purpose: Shows how to prevent duplicate submissions by using tokens // Example code for Chapter 4.4 based off the code from Chapter 4.2 // Run `go run main.go` then access http://localhost:9090 package main import ( "apps/ch.4.4/nonce" "apps/ch.4.4/validator" "html/template" "log" "net/http" ) const ( PORT = "9090" HOST_URL = "http://localhost:" + PORT ) var submissions nonce.Nonces var t *template.Template func index(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, HOST_URL+"/profile", http.StatusTemporaryRedirect) } func profileHandler(w http.ResponseWriter, r *http.Request) { t.ExecuteTemplate(w, "profile", submissions.NewNonce()) } func checkProfile(w http.ResponseWriter, r *http.Request) { var errs validator.Errors r.ParseForm() token := r.Form.Get("token") if err := submissions.CheckThenMarkToken(token); err != nil { errs = validator.Errors{[]error{err}} } else { p := validator.ProfilePage{&r.Form} errs = p.GetErrors() } t.ExecuteTemplate(w, "submission", errs) } func init() { submissions = nonce.New() t = template.Must(template.ParseFiles("profile.gtpl", "submission.gtpl")) } func main() { http.HandleFunc("/", index) http.HandleFunc("/profile", profileHandler) http.HandleFunc("/checkprofile", checkProfile) err := http.ListenAndServe(":"+PORT, nil) // setting listening port if err != nil { log.Fatal("ListenAndServe: ", err) } }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.4.4/nonce/main.go
pt-br/code/src/apps/ch.4.4/nonce/main.go
// A nonce is a number or string used only once. // This is useful for generating a unique token for login pages to prevent duplicate submissions. package nonce import ( "crypto/md5" "errors" "fmt" "io" "math/rand" "strconv" "time" ) // Contains a unique token type Nonce struct { Token string } // Keeps track of marked/used tokens type Nonces struct { hashs map[string]bool } func New() Nonces { return Nonces{make(map[string]bool)} } func (n *Nonces) NewNonce() Nonce { return Nonce{n.NewToken()} } // Returns a new unique token func (n *Nonces) NewToken() string { t := createToken() for n.HasToken(t) { t = createToken() } return t } // Checks if token has been marked. func (n *Nonces) HasToken(token string) bool { return n.hashs[token] == true } func (n *Nonces) MarkToken(token string) { n.hashs[token] = true } func (n *Nonces) CheckToken(token string) error { if token == "" { return errors.New("No token supplied") } if n.HasToken(token) { return errors.New("Duplicate submission.") } return nil } func (n *Nonces) CheckThenMarkToken(token string) error { defer n.MarkToken(token) if err := n.CheckToken(token); err != nil { return err } return nil } func createToken() string { h := md5.New() now := time.Now().Unix() io.WriteString(h, strconv.FormatInt(now, 10)) io.WriteString(h, strconv.FormatInt(rand.Int63(), 10)) return fmt.Sprintf("%x", h.Sum(nil)) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.4.4/validator/main.go
pt-br/code/src/apps/ch.4.4/validator/main.go
// This file contains all the validators to validate the profile page. package validator import ( "errors" "fmt" "net/url" "regexp" "strconv" "strings" "time" ) type ProfilePage struct { Form *url.Values } type Errors struct { Errors []error } // Goes through the form object and validates each element. // Attachs an error to the output if validation fails. func (p *ProfilePage) GetErrors() Errors { errs := make([]error, 0, 10) if *p.Form == nil || len(*p.Form) < 1 { errs = append(errs, errors.New("No data was received. Please submit from the profile page.")) } for name, val := range *p.Form { if fn, ok := stringValidator[name]; ok { if err := fn(strings.Join(val, "")); err != nil { errs = append(errs, err) } } else { if fn, ok := stringsValidator[name]; ok { if err := fn(val); err != nil { errs = append(errs, err) } } } } return Errors{errs} } const ( // Used for parsing the time mmddyyyyForm = "01/02/2006" // we want the date sent in this format yyyymmddForm = "2006-01-02" // However, HTML5 pages send the date in this format ) var stringValidator map[string]func(string) error = map[string]func(string) error{ // parameter name : validator reference "age": checkAge, "birthday": checkDate, "chineseName": checkChineseName, "email": checkEmail, "gender": checkGender, "shirtsize": checkShirtSize, "username": checkUsername, } var stringsValidator map[string]func([]string) error = map[string]func([]string) error{ // parameter name : validator reference "sibling": checkSibling, } // Returns true if slices have a common element func doSlicesIntersect(s1, s2 []string) bool { if s1 == nil || s2 == nil { return false } for _, str := range s1 { if isElementInSlice(str, s2) { return true } } return false } func isElementInSlice(str string, sl []string) bool { if sl == nil || str == "" { return false } for _, v := range sl { if v == str { return true } } return false } // Checks if all the characters are chinese characters. Won't check if empty.' func checkChineseName(str string) error { if str != "" { if m, _ := regexp.MatchString("^[\\x{4e00}-\\x{9fa5}]+$", strings.Trim(str, " ")); !m { return errors.New("Please make sure that the chinese name only contains chinese characters.") } } return nil } // Checks if a user name exist. func checkUsername(str string) error { if strings.Trim(str, " ") == "" { return errors.New("Please enter a username.") } return nil } // Check if age is a number and between 13 and 130 func checkAge(str string) error { age, err := strconv.Atoi(str) if str == "" || err != nil { return errors.New("Please enter a valid age.") } if age < 13 { return errors.New("You must be at least 13 years of age to submit.") } if age > 130 { return errors.New("You're too old to register, grandpa.") } return nil } func checkEmail(str string) error { if m, err := regexp.MatchString(`^[^@]+@[^@]+$`, str); !m { fmt.Println("err = ", err) return errors.New("Please enter a valid email address.") } return nil } // Checks if a valid date was passed. func checkDate(str string) error { _, err := time.Parse(mmddyyyyForm, str) if err != nil { _, err = time.Parse(yyyymmddForm, str) } if str == "" || err != nil { return errors.New("Please enter a valid Date.") } return nil } // Checks if the passed input is a known gender option func checkGender(str string) error { if str == "" { return nil } siblings := []string{"m", "f", "na"} if !isElementInSlice(str, siblings) { return errors.New("Please select a valid gender.") } return nil } // Check if all the values are known options. func checkSibling(strs []string) error { if strs == nil || len(strs) < 1 { return nil } siblings := []string{"m", "f"} if siblings != nil && !doSlicesIntersect(siblings, strs) { return errors.New("Please select a valid sibling") } return nil } // Checks if the shirt size is a known option. func checkShirtSize(str string) error { if str == "" { return nil } shirts := []string{"s", "m", "l", "xl", "xxl"} if !isElementInSlice(str, shirts) { return errors.New("Please select a valid shirt size") } return nil }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.5.2/main.go
pt-br/code/src/apps/ch.5.2/main.go
// Example code for Chapter 5.2 from "Build Web Application with Golang" // Purpose: Use SQL driver to perform simple CRUD operations. package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) const ( DB_USER = "user" DB_PASSWORD = "" DB_NAME = "test" ) func main() { dbSouce := fmt.Sprintf("%v:%v@/%v?charset=utf8", DB_USER, DB_PASSWORD, DB_NAME) db, err := sql.Open("mysql", dbSouce) checkErr(err) defer db.Close() fmt.Println("Inserting") stmt, err := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?") checkErr(err) res, err := stmt.Exec("astaxie", "software developement", "2012-12-09") checkErr(err) id, err := res.LastInsertId() checkErr(err) fmt.Println("id of last inserted row =", id) fmt.Println("Updating") stmt, err = db.Prepare("update userinfo set username=? where uid=?") checkErr(err) res, err = stmt.Exec("astaxieupdate", id) checkErr(err) affect, err := res.RowsAffected() checkErr(err) fmt.Println(affect, "row(s) changed") fmt.Println("Querying") rows, err := db.Query("SELECT * FROM userinfo") checkErr(err) for rows.Next() { var uid int var username, department, created string err = rows.Scan(&uid, &username, &department, &created) checkErr(err) fmt.Println("uid | username | department | created") fmt.Printf("%3v | %6v | %6v | %6v\n", uid, username, department, created) } fmt.Println("Deleting") stmt, err = db.Prepare("delete from userinfo where uid=?") checkErr(err) res, err = stmt.Exec(id) checkErr(err) affect, err = res.RowsAffected() checkErr(err) fmt.Println(affect, "row(s) changed") } func checkErr(err error) { if err != nil { panic(err) } }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.3/main.go
pt-br/code/src/apps/ch.2.3/main.go
// Código de exemplo do capítulo 2.3 de "Build Web Application with Golang" // Propósito: mostra alguns exemplos de if, else, switch, loops e defer. package main import "fmt" func computedValue() int { return 1 } func show_if() { fmt.Println("\n#show_if()") x := computedValue() integer := 23 fmt.Println("x =", x) fmt.Println("integer =", integer) if x > 10 { fmt.Println("x is greater than 10") } else { fmt.Println("x is less than 10") } if integer == 3 { fmt.Println("The integer is equal to 3") } else if integer < 3 { fmt.Println("The integer is less than 3") } else { fmt.Println("The integer is greater than 3") } } func show_if_var() { fmt.Println("\n#show_if_var()") // inicializa x, então verifica se x é maior if x := computedValue(); x > 10 { fmt.Println("x is greater than 10") } else { fmt.Println("x is less than 10") } // o seguinte código não irá compilar, porque `x` é acessível apenas pelo bloco if/else // fmt.Println(x) } func show_goto() { fmt.Println("\n#show_goto()") // A chamada para o label altera o fluxo da goroutine. i := 0 Here: // label termina com ":" fmt.Println(i) i++ if i < 10 { goto Here // pule para label "Here" } } func show_for_loop() { fmt.Println("\n#show_for_loop()") sum := 0 for index := 0; index < 10; index++ { sum += index } fmt.Println("part 1, sum is equal to ", sum) sum = 1 // O compilador irá remover o `;` da linha abaixo. // for ; sum < 1000 ; { for sum < 1000 { sum += sum } fmt.Println("part 2, sum is equal to ", sum) for index := 10; 0 < index; index-- { if index == 5 { break // ou continue } fmt.Println(index) } } func show_loop_through_map() { fmt.Println("\n#show_loop_through_map()") m := map[string]int{ "one": 1, "two": 2, "three": 3, } fmt.Println("map value = ", m) for k, v := range m { fmt.Println("map's key: ", k) fmt.Println("map's value: ", v) } } func show_switch() { fmt.Println("\n#show_switch()") i := 10 switch i { case 1: fmt.Println("i is equal to 1") case 2, 3, 4: fmt.Println("i is equal to 2, 3 or 4") case 10: fmt.Println("i is equal to 10") default: fmt.Println("All I know is that i is an integer") } integer := 6 fmt.Println("integer =", integer) switch integer { case 4: fmt.Println("integer == 4") fallthrough case 5: fmt.Println("integer <= 5") fallthrough case 6: fmt.Println("integer <= 6") fallthrough case 7: fmt.Println("integer <= 7") fallthrough case 8: fmt.Println("integer <= 8") fallthrough default: fmt.Println("default case") } } func show_defer() { fmt.Println("\nshow_defer()") defer fmt.Println("(last defer)") for i := 0; i < 5; i++ { defer fmt.Printf("%d ", i) } } func main() { show_if() show_if_var() show_goto() show_for_loop() show_loop_through_map() show_switch() show_defer() }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.3/import_packages/main.go
pt-br/code/src/apps/ch.2.3/import_packages/main.go
// Código de exemplo do capítulo 2.3 de "Build Web Application with Golang" // Propósito: mostra diferentes formas de importar um pacote. // Nota: para o pacote `only_call_init`, fazemos referência ao caminho a partir do diretório // base de `$GOPATH/src`. Golang desencoraja o uso de caminhos relativos para importar pacotes. // BAD: "./only_call_init" // GOOD: "apps/ch.2.3/import_packages/only_call_init" package main import ( // `_` irá chamar apenas init() dentro do pacote only_call_init _ "apps/ch.2.3/import_packages/only_call_init" f "fmt" // importa o pacote como `f` . "math" // torna os métodos públicos e constantes globais "mymath" // pacote personalizado localizado em $GOPATH/src/ "os" // import normal de um pacote padrão "text/template" // o pacote leva o nome do último caminho da pasta, `template` ) func main() { f.Println("mymath.Sqrt(4) =", mymath.Sqrt(4)) f.Println("E =", E) // referencia math.E t, _ := template.New("test").Parse("Pi^2 = {{.}}") t.Execute(os.Stdout, Pow(Pi, 2)) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.3/import_packages/only_call_init/only_call_init.go
pt-br/code/src/apps/ch.2.3/import_packages/only_call_init/only_call_init.go
package only_call_init import "fmt" func init() { fmt.Println("only_call_init.init() was called.") }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.3/type_function/main.go
pt-br/code/src/apps/ch.2.3/type_function/main.go
// Código de exemplo do capítulo 2.3 de "Build Web Application with Golang" // Propósito: mostra como definir um tipo de função package main import "fmt" type testInt func(int) bool // define uma função como um tipo de variável func isOdd(integer int) bool { if integer%2 == 0 { return false } return true } func isEven(integer int) bool { if integer%2 == 0 { return true } return false } // passa a função `f` como um argumento para outra função func filter(slice []int, f testInt) []int { var result []int for _, value := range slice { if f(value) { result = append(result, value) } } return result } func init() { fmt.Println("\n#init() was called.") } func main() { slice := []int{1, 2, 3, 4, 5, 7} fmt.Println("slice = ", slice) odd := filter(slice, isOdd) // usa funções como valores fmt.Println("Odd elements of slice are: ", odd) even := filter(slice, isEven) fmt.Println("Even elements of slice are: ", even) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.3/variadic_functions/main.go
pt-br/code/src/apps/ch.2.3/variadic_functions/main.go
// Código de exemplo do capítulo 2.3 de "Build Web Application with Golang" // Propósito: mostra como retornar múltiplos valores de uma função package main import "fmt" // retorna os resultados de A + B e A * B func SumAndProduct(A, B int) (int, int) { return A + B, A * B } func main() { x := 3 y := 4 xPLUSy, xTIMESy := SumAndProduct(x, y) fmt.Printf("%d + %d = %d\n", x, y, xPLUSy) fmt.Printf("%d * %d = %d\n", x, y, xTIMESy) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.3/hidden_print_methods/main.go
pt-br/code/src/apps/ch.2.3/hidden_print_methods/main.go
// A partir do Google go 1.1.2, `println()` e `print()` são funções ocultas incluídas no pacote de tempo de execução. // No entanto, é encorajado utilizar as funções de impressão do pacote `fmt` package main import "fmt" func f() { fmt.Println("First") print("Second ") println(" Third") } func main() { f() }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.3/panic_and_recover/main.go
pt-br/code/src/apps/ch.2.3/panic_and_recover/main.go
// Código de exemplo do capítulo 2.3 de "Build Web Application with Golang" // Propósito: mostrar como usar `panic()` e `recover()` package main import ( "fmt" "os" ) var user = os.Getenv("USER") func check_user() { if user == "" { panic("no value for $USER") } fmt.Println("Environment Variable `USER` =", user) } func throwsPanic(f func()) (b bool) { defer func() { if x := recover(); x != nil { fmt.Println("Panic message =", x); b = true } }() f() // se f causar pânico, isto irá recuperar return } func main(){ didPanic := throwsPanic(check_user) fmt.Println("didPanic =", didPanic) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.3/basic_functions/main.go
pt-br/code/src/apps/ch.2.3/basic_functions/main.go
// Código de exemplo do capítulo 2.3 de "Build Web Application with Golang" // Propósito: Criando uma função básica package main import "fmt" // retorna o maior valor entre a e b func max(a, b int) int { if a > b { return a } return b } func main() { x := 3 y := 4 z := 5 max_xy := max(x, y) // chama a função max(x, y) max_xz := max(x, z) // chama a função max(x, z) fmt.Printf("max(%d, %d) = %d\n", x, y, max_xy) fmt.Printf("max(%d, %d) = %d\n", x, z, max_xz) fmt.Printf("max(%d, %d) = %d\n", y, z, max(y, z)) // chama a função aqui }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.3/pass_by_value_and_pointer/main.go
pt-br/code/src/apps/ch.2.3/pass_by_value_and_pointer/main.go
// Código de exemplo do capítulo 2.3 de "Build Web Application with Golang" // Propósito: mostra como passar uma variável por valor e por referência package main import "fmt" func add_by_value(a int) int { a = a + 1 return a } func add_by_reference(a *int) int { *a = *a + 1 return *a } func show_add_by_value() { x := 3 fmt.Println("x = ", x) fmt.Println("add_by_value(x) =", add_by_value(x) ) fmt.Println("x = ", x) } func show_add_by_reference() { x := 3 fmt.Println("x = ", x) // &x passa o endereço de memória de x fmt.Println("add_by_reference(&x) =", add_by_reference(&x) ) fmt.Println("x = ", x) } func main() { show_add_by_value() show_add_by_reference() }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.4.3/main.go
pt-br/code/src/apps/ch.4.3/main.go
// Example code for Chapter 4.3 from "Build Web Application with Golang" // Purpose: Shows how to properly escape input package main import ( "html/template" "net/http" textTemplate "text/template" ) var t *template.Template = template.Must(template.ParseFiles("index.gtpl")) func index(w http.ResponseWriter, r *http.Request) { r.ParseForm() userInput := r.Form.Get("userinput") if 0 < len(r.Form.Get("escape")) { t.Execute(w, template.HTMLEscapeString(userInput)) } else { // Variables with type `template.HTML` are not escaped when passed to `.Execute()` t.Execute(w, template.HTML(userInput)) } } func templateHandler(w http.ResponseWriter, r *http.Request) { r.ParseForm() userInput := r.Form.Get("userinput") if 0 < len(r.Form.Get("escape")) { // `html/template.Execute()` escapes input t.Execute(w, userInput) } else { tt := textTemplate.Must(textTemplate.ParseFiles("index.gtpl")) // `text/template.Execute()` doesn't escape input tt.Execute(w, userInput) } } func main() { http.HandleFunc("/", index) http.HandleFunc("/template", templateHandler) http.ListenAndServe(":9090", nil) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.1.2/main.go
pt-br/code/src/apps/ch.1.2/main.go
// Código de exemplo para o Capítulo 1.2 do "Build Web Application with Golang" // Propósito: Execute este arquivo para verificar se o seu workspace está corretamente configurado. // Para executar, navegue até o diretório onde ele estiver salvo e digite no console `go run main.go` // Se o texto "Hello World" não aparecer, então configure seu ambiente novamente. package main import ( "fmt" "mymath" ) func main() { fmt.Printf("Hello, world. Sqrt(2) = %v\n", mymath.Sqrt(2)) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.7/select_channel/main.go
pt-br/code/src/apps/ch.2.7/select_channel/main.go
// Example code for Chapter 2.7 from "Build Web Application with Golang" // Purpose: Shows how to use `select` package main import "fmt" func fibonacci(c, quit chan int) { x, y := 1, 1 for { select { case c <- x: x, y = y, x+y case <-quit: fmt.Println("quit") return } } } func main() { c := make(chan int) quit := make(chan int) go func() { for i := 0; i < 10; i++ { fmt.Println(<-c) } quit <- 0 }() fibonacci(c, quit) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.7/buffered_channel/main.go
pt-br/code/src/apps/ch.2.7/buffered_channel/main.go
// Example code for Chapter 2.7 from "Build Web Application with Golang" // Purpose: Shows how to use a buffered channel package main import "fmt" func main() { c := make(chan int, 2) // change 2 to 1 will have runtime error, but 3 is fine c <- 1 c <- 2 fmt.Println(<-c) fmt.Println(<-c) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.7/goroutine/main.go
pt-br/code/src/apps/ch.2.7/goroutine/main.go
// Example code for Chapter 2.7 from "Build Web Application with Golang" // Purpose: Shows how to launch a simple gorountine package main import ( "fmt" "runtime" ) func say(s string) { for i := 0; i < 5; i++ { runtime.Gosched() fmt.Println(s) } } func main() { go say("world") // create a new goroutine say("hello") // current goroutine }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.7/range_and_close_channel/main.go
pt-br/code/src/apps/ch.2.7/range_and_close_channel/main.go
// Example code for Chapter 2.7 from "Build Web Application with Golang" // Purpose: Shows how to close and interate through a channel package main import ( "fmt" ) func fibonacci(n int, c chan int) { x, y := 1, 1 for i := 0; i < n; i++ { c <- x x, y = y, x+y } close(c) } func main() { c := make(chan int, 10) go fibonacci(cap(c), c) for i := range c { fmt.Println(i) } }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.7/unbuffered_channel/main.go
pt-br/code/src/apps/ch.2.7/unbuffered_channel/main.go
// Example code for Chapter 2.7 from "Build Web Application with Golang" // Purpose: Shows how to create and use a unbuffered channel package main import "fmt" func sum(a []int, c chan int) { total := 0 for _, v := range a { total += v } c <- total // send total to c } func main() { a := []int{7, 2, 8, -9, 4, 0} c := make(chan int) go sum(a[:len(a)/2], c) go sum(a[len(a)/2:], c) x, y := <-c, <-c // receive from c fmt.Println(x, y, x+y) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.7/timeout/main.go
pt-br/code/src/apps/ch.2.7/timeout/main.go
// Example code for Chapter 2.7 from "Build Web Application with Golang" // Purpose: Shows how to create and use a timeout package main import ( "fmt" "time" ) func main() { c := make(chan int) o := make(chan bool) go func() { for { select { case v := <-c: fmt.Println(v) case <-time.After(5 * time.Second): fmt.Println("timeout") o <- true break } } }() <-o }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.3.4/main.go
pt-br/code/src/apps/ch.3.4/main.go
// Example code for Chapter 3.4 from "Build Web Application with Golang" // Purpose: Shows how to create a handler for `http.ListenAndServe()` // Run `go run main.go` then access `http://localhost:9090` package main import ( "fmt" "net/http" ) type MyMux struct { } func (p *MyMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/" { sayhelloName(w, r) return } http.NotFound(w, r) return } func sayhelloName(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello myroute!") } func main() { mux := &MyMux{} http.ListenAndServe(":9090", mux) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.5.6/mongodb/main.go
pt-br/code/src/apps/ch.5.6/mongodb/main.go
// Example code for Chapter 5.6 from "Build Web Application with Golang" // Purpose: Shows you have to perform basic CRUD operations for a mongodb driver. package main import ( "fmt" "labix.org/v2/mgo" "labix.org/v2/mgo/bson" ) type Person struct { Name string Phone string } func checkError(err error) { if err != nil { panic(err) } } const ( DB_NAME = "test" DB_COLLECTION = "people" ) func main() { session, err := mgo.Dial("localhost") checkError(err) defer session.Close() session.SetMode(mgo.Monotonic, true) c := session.DB(DB_NAME).C(DB_COLLECTION) err = c.DropCollection() checkError(err) ale := Person{"Ale", "555-5555"} cla := Person{"Cla", "555-1234"} fmt.Println("Inserting") err = c.Insert(&ale, &cla) checkError(err) fmt.Println("Updating") ale.Phone = "555-0101" err = c.Update(bson.M{"name": "Ale"}, &ale) fmt.Println("Querying") result := Person{} err = c.Find(bson.M{"name": "Ale"}).One(&result) checkError(err) fmt.Println("Phone:", result.Phone) fmt.Println("Deleting") err = c.Remove(bson.M{"name": "Ale"}) checkError(err) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.5.6/redis/main.go
pt-br/code/src/apps/ch.5.6/redis/main.go
// Example code for Chapter 5.6 from "Build Web Application with Golang" // Purpose: Shows you have to perform basic CRUD operations for a redis driver. package main import ( "fmt" "github.com/astaxie/goredis" ) func checkError(err error) { if err != nil { panic(err) } } const ( DB_PORT = "9191" DB_URL = "127.0.0.1" ) func main() { var client goredis.Client // Set the default port in Redis client.Addr = DB_URL + ":" + DB_PORT // string manipulation fmt.Println("Inserting") err := client.Set("a", []byte("hello")) checkError(err) // list operation vals := []string{"a", "b", "c", "d"} for _, v := range vals { err = client.Rpush("l", []byte(v)) checkError(err) } fmt.Println("Updating") err = client.Set("a", []byte("a is for apple")) checkError(err) err = client.Rpush("l", []byte("e")) checkError(err) fmt.Println("Querying") val, err := client.Get("a") checkError(err) fmt.Println(string(val)) dbvals, err := client.Lrange("l", 0, 4) checkError(err) for i, v := range dbvals { println(i, ":", string(v)) } fmt.Println("Deleting") _, err = client.Del("l") checkError(err) _, err = client.Del("a") checkError(err) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.5/attach_methods_to_struct/main.go
pt-br/code/src/apps/ch.2.5/attach_methods_to_struct/main.go
// Example code from Chapter 2.5 // Attach method to struct. package main import ( "fmt" "math" ) type Rectangle struct { width, height float64 } type Circle struct { radius float64 } func (r Rectangle) area() float64 { return r.width * r.height } func (c Circle) area() float64 { return c.radius * c.radius * math.Pi } func main() { r1 := Rectangle{12, 2} r2 := Rectangle{9, 4} c1 := Circle{10} c2 := Circle{25} fmt.Println("Area of r1 is: ", r1.area()) fmt.Println("Area of r2 is: ", r2.area()) fmt.Println("Area of c1 is: ", c1.area()) fmt.Println("Area of c2 is: ", c2.area()) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.5/method_overload/main.go
pt-br/code/src/apps/ch.2.5/method_overload/main.go
package main import "fmt" type Human struct { name string age int phone string } type Student struct { Human school string } type Employee struct { Human company string } func (h *Human) SayHi() { fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone) } func (e *Employee) SayHi() { fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name, e.company, e.phone) //Yes you can split into 2 lines here. } func main() { mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"} sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"} mark.SayHi() sam.SayHi() }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.5/pass_struct_to_method/main.go
pt-br/code/src/apps/ch.2.5/pass_struct_to_method/main.go
package main import "fmt" type Rectangle struct { width, height float64 } func area(r Rectangle) float64 { return r.width * r.height } func main() { r1 := Rectangle{12, 2} r2 := Rectangle{9, 4} fmt.Println("Area of r1 is: ", area(r1)) fmt.Println("Area of r2 is: ", area(r2)) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.5/box_example/main.go
pt-br/code/src/apps/ch.2.5/box_example/main.go
package main import "fmt" const ( WHITE = iota BLACK BLUE RED YELLOW ) type Color byte type Box struct { width, height, depth float64 color Color } type BoxList []Box //a slice of boxes func (b Box) Volume() float64 { return b.width * b.height * b.depth } func (b *Box) SetColor(c Color) { b.color = c } func (bl BoxList) BiggestsColor() Color { v := 0.00 k := Color(WHITE) for _, b := range bl { if b.Volume() > v { v = b.Volume() k = b.color } } return k } func (bl BoxList) PaintItBlack() { for i, _ := range bl { bl[i].SetColor(BLACK) } } func (c Color) String() string { strings := []string{"WHITE", "BLACK", "BLUE", "RED", "YELLOW"} return strings[c] } func main() { boxes := BoxList{ Box{4, 4, 4, RED}, Box{10, 10, 1, YELLOW}, Box{1, 1, 20, BLACK}, Box{10, 10, 1, BLUE}, Box{10, 30, 1, WHITE}, Box{20, 20, 20, YELLOW}, } fmt.Printf("We have %d boxes in our set\n", len(boxes)) fmt.Println("The volume of the first one is", boxes[0].Volume(), "cm³") fmt.Println("The color of the last one is", boxes[len(boxes)-1].color.String()) fmt.Println("The biggest one is", boxes.BiggestsColor().String()) fmt.Println("Let's paint them all black") boxes.PaintItBlack() fmt.Println("The color of the second one is", boxes[1].color.String()) fmt.Println("Obviously, now, the biggest one is", boxes.BiggestsColor().String()) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.5/embedded_method/main.go
pt-br/code/src/apps/ch.2.5/embedded_method/main.go
package main import "fmt" type Human struct { name string age int phone string } type Student struct { Human // anonymous field school string } type Employee struct { Human company string } // define a method in Human func (h *Human) SayHi() { fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone) } func main() { mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"} sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"} mark.SayHi() sam.SayHi() }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.6/switch_type_check/main.go
pt-br/code/src/apps/ch.2.6/switch_type_check/main.go
package main import ( "fmt" "strconv" ) type Element interface{} type List []Element type Person struct { name string age int } func (p Person) String() string { return "(name: " + p.name + " - age: " + strconv.Itoa(p.age) + " years)" } func main() { list := make(List, 3) list[0] = 1 //an int list[1] = "Hello" //a string list[2] = Person{"Dennis", 70} for index, element := range list { switch value := element.(type) { case int: fmt.Printf("list[%d] is an int and its value is %d\n", index, value) case string: fmt.Printf("list[%d] is a string and its value is %s\n", index, value) case Person: fmt.Printf("list[%d] is a Person and its value is %s\n", index, value) default: fmt.Println("list[%d] is of a different type", index) } } }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.6/reflection/main.go
pt-br/code/src/apps/ch.2.6/reflection/main.go
package main import ( "fmt" "reflect" ) func show_interface_none() { fmt.Println("\nshow_interface_none()") var a interface{} a = "string" a = 1 a = false fmt.Println("a =", a) } func show_reflection() { fmt.Println("\nshow_reflection()") var x float64 = 3.4 v := reflect.ValueOf(x) fmt.Println("type:", v.Type()) fmt.Println("kind is float64:", v.Kind() == reflect.Float64) fmt.Println("value:", v.Float()) p := reflect.ValueOf(&x) newX := p.Elem() newX.SetFloat(7.1) fmt.Println("newX =", newX) fmt.Println("newX float64() value:", newX.Float()) } func main() { show_interface_none() show_reflection() }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.6/interface/main.go
pt-br/code/src/apps/ch.2.6/interface/main.go
package main import "fmt" type Human struct { name string age int phone string } type Student struct { Human school string loan float32 } type Employee struct { Human company string money float32 } func (h Human) SayHi() { fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone) } func (h Human) Sing(lyrics string) { fmt.Println("La la la la...", lyrics) } func (e Employee) SayHi() { fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name, e.company, e.phone) //Yes you can split into 2 lines here. } // Interface Men implemented by Human, Student and Employee type Men interface { SayHi() Sing(lyrics string) } func main() { mike := Student{Human{"Mike", 25, "222-222-XXX"}, "MIT", 0.00} paul := Student{Human{"Paul", 26, "111-222-XXX"}, "Harvard", 100} sam := Employee{Human{"Sam", 36, "444-222-XXX"}, "Golang Inc.", 1000} Tom := Employee{Human{"Sam", 36, "444-222-XXX"}, "Things Ltd.", 5000} // define interface i var i Men //i can store Student i = mike fmt.Println("This is Mike, a Student:") i.SayHi() i.Sing("November rain") //i can store Employee i = Tom fmt.Println("This is Tom, an Employee:") i.SayHi() i.Sing("Born to be wild") // slice of Men fmt.Println("Let's use a slice of Men and see what happens") x := make([]Men, 3) // these three elements are different types but they all implemented interface Men x[0], x[1], x[2] = paul, sam, mike for _, value := range x{ value.SayHi() } }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.6/stringer_interface/main.go
pt-br/code/src/apps/ch.2.6/stringer_interface/main.go
package main import ( "fmt" "strconv" ) type Human struct { name string age int phone string } // Human implemented fmt.Stringer func (h Human) String() string { return "Name:" + h.name + ", Age:" + strconv.Itoa(h.age) + " years, Contact:" + h.phone } func main() { Bob := Human{"Bob", 39, "000-7777-XXX"} fmt.Println("This Human is : ", Bob) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.6/type_check/main.go
pt-br/code/src/apps/ch.2.6/type_check/main.go
package main import ( "fmt" "strconv" ) type Element interface{} type List []Element type Person struct { name string age int } func (p Person) String() string { return "(name: " + p.name + " - age: " + strconv.Itoa(p.age) + " years)" } func main() { list := make(List, 3) list[0] = 1 // an int list[1] = "Hello" // a string list[2] = Person{"Dennis", 70} for index, element := range list { if value, ok := element.(int); ok { fmt.Printf("list[%d] is an int and its value is %d\n", index, value) } else if value, ok := element.(string); ok { fmt.Printf("list[%d] is a string and its value is %s\n", index, value) } else if value, ok := element.(Person); ok { fmt.Printf("list[%d] is a Person and its value is %s\n", index, value) } else { fmt.Println("list[%d] is of a different type", index) } } }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.3.2/main.go
pt-br/code/src/apps/ch.3.2/main.go
// Example code for Chapter 3.2 from "Build Web Application with Golang" // Purpose: Shows how to acces the form values from the request package main import ( "fmt" "log" "net/http" "strings" ) func sayhelloName(w http.ResponseWriter, r *http.Request) { r.ParseForm() // parse arguments, you have to call this by yourself fmt.Println(r.Form) // print form information in server side fmt.Println("path", r.URL.Path) fmt.Println("scheme", r.URL.Scheme) fmt.Println(r.Form["url_long"]) for k, v := range r.Form { fmt.Println("key:", k) fmt.Println("val:", strings.Join(v, "")) } fmt.Fprintf(w, "Hello astaxie!") // send data to client side } func main() { http.HandleFunc("/", sayhelloName) // set router err := http.ListenAndServe(":9090", nil) // set listen port if err != nil { log.Fatal("ListenAndServe: ", err) } }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.4.2/main.go
pt-br/code/src/apps/ch.4.2/main.go
// Example code for Chapter 4.2 from "Build Web Application with Golang" // Purpose: Shows how to perform server-side validation of user input from a form. // Also shows to use multiple template files with predefined template names. // Run `go run main.go` and then access http://localhost:9090 package main import ( "apps/ch.4.2/validator" "html/template" "log" "net/http" ) const ( PORT = "9090" HOST_URL = "http://localhost:" + PORT ) var t *template.Template type Links struct { BadLinks [][2]string } // invalid links to display for testing. var links Links func index(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, HOST_URL+"/profile", http.StatusTemporaryRedirect) } func profileHandler(w http.ResponseWriter, r *http.Request) { t.ExecuteTemplate(w, "profile", links) } func checkProfile(w http.ResponseWriter, r *http.Request) { r.ParseForm() p := validator.ProfilePage{&r.Form} t.ExecuteTemplate(w, "submission", p.GetErrors()) } // This function is called before main() func init() { // Note: we can reference the loaded templates by their defined name inside the template files. t = template.Must(template.ParseFiles("profile.gtpl", "submission.gtpl")) list := make([][2]string, 2) list[0] = [2]string{HOST_URL + "/checkprofile", "No data"} list[1] = [2]string{HOST_URL + "/checkprofile?age=1&gender=guy&shirtsize=big", "Invalid options"} links = Links{list} } func main() { http.HandleFunc("/", index) http.HandleFunc("/profile", profileHandler) http.HandleFunc("/checkprofile", checkProfile) err := http.ListenAndServe(":"+PORT, nil) // setting listening port if err != nil { log.Fatal("ListenAndServe: ", err) } }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.4.2/validator/main.go
pt-br/code/src/apps/ch.4.2/validator/main.go
// This file contains all the validators to validate the profile page. package validator import ( "errors" "fmt" "net/url" "regexp" "strconv" "strings" "time" ) type ProfilePage struct { Form *url.Values } type Errors struct { Errors []error } // Goes through the form object and validates each element. // Attachs an error to the output if validation fails. func (p *ProfilePage) GetErrors() Errors { errs := make([]error, 0, 10) if *p.Form == nil || len(*p.Form) < 1 { errs = append(errs, errors.New("No data was received. Please submit from the profile page.")) } for name, val := range *p.Form { if fn, ok := stringValidator[name]; ok { if err := fn(strings.Join(val, "")); err != nil { errs = append(errs, err) } } else { if fn, ok := stringsValidator[name]; ok { if err := fn(val); err != nil { errs = append(errs, err) } } } } return Errors{errs} } const ( // Used for parsing the time mmddyyyyForm = "01/02/2006" // we want the date sent in this format yyyymmddForm = "2006-01-02" // However, HTML5 pages send the date in this format ) var stringValidator map[string]func(string) error = map[string]func(string) error{ // parameter name : validator reference "age": checkAge, "birthday": checkDate, "chineseName": checkChineseName, "email": checkEmail, "gender": checkGender, "shirtsize": checkShirtSize, "username": checkUsername, } var stringsValidator map[string]func([]string) error = map[string]func([]string) error{ // parameter name : validator reference "sibling": checkSibling, } // Returns true if slices have a common element func doSlicesIntersect(s1, s2 []string) bool { if s1 == nil || s2 == nil { return false } for _, str := range s1 { if isElementInSlice(str, s2) { return true } } return false } func isElementInSlice(str string, sl []string) bool { if sl == nil || str == "" { return false } for _, v := range sl { if v == str { return true } } return false } // Checks if all the characters are chinese characters. Won't check if empty.' func checkChineseName(str string) error { if str != "" { if m, _ := regexp.MatchString("^[\\x{4e00}-\\x{9fa5}]+$", strings.Trim(str, " ")); !m { return errors.New("Please make sure that the chinese name only contains chinese characters.") } } return nil } // Checks if a user name exist. func checkUsername(str string) error { if strings.Trim(str, " ") == "" { return errors.New("Please enter a username.") } return nil } // Check if age is a number and between 13 and 130 func checkAge(str string) error { age, err := strconv.Atoi(str) if str == "" || err != nil { return errors.New("Please enter a valid age.") } if age < 13 { return errors.New("You must be at least 13 years of age to submit.") } if age > 130 { return errors.New("You're too old to register, grandpa.") } return nil } func checkEmail(str string) error { if m, err := regexp.MatchString(`^[^@]+@[^@]+$`, str); !m { fmt.Println("err = ", err) return errors.New("Please enter a valid email address.") } return nil } // Checks if a valid date was passed. func checkDate(str string) error { _, err := time.Parse(mmddyyyyForm, str) if err != nil { _, err = time.Parse(yyyymmddForm, str) } if str == "" || err != nil { return errors.New("Please enter a valid Date.") } return nil } // Checks if the passed input is a known gender option func checkGender(str string) error { if str == "" { return nil } siblings := []string{"m", "f", "na"} if !isElementInSlice(str, siblings) { return errors.New("Please select a valid gender.") } return nil } // Check if all the values are known options. func checkSibling(strs []string) error { if strs == nil || len(strs) < 1 { return nil } siblings := []string{"m", "f"} if siblings != nil && !doSlicesIntersect(siblings, strs) { return errors.New("Please select a valid sibling") } return nil } // Checks if the shirt size is a known option. func checkShirtSize(str string) error { if str == "" { return nil } shirts := []string{"s", "m", "l", "xl", "xxl"} if !isElementInSlice(str, shirts) { return errors.New("Please select a valid shirt size") } return nil }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.2/main.go
pt-br/code/src/apps/ch.2.2/main.go
// Código de exemplo para o Capítulo 2.2 do "Build Web Application with Golang" // Propósito: Revisar os conceitos de atribuição e manipulação de tipos de dados básicos. package main import ( "errors" "fmt" ) // constantes const Pi = 3.1415926 // booleanos: padrão `false` var isActive bool // variável global var enabled, disabled = true, false // omite o tipo das variáveis // definições agrupadas const ( i = 1e4 MaxThread = 10 prefix = "astaxie_" ) var ( frenchHello string // forma básica para definir strings emptyString string = "" // define uma string vazia ) func show_multiple_assignments() { fmt.Println("show_multiple_assignments()") var v1 int = 42 // Define três variáveis com o tipo "int" e inicializa seus valores. // vname1 é v1, vname2 é v2, vname3 é v3 var v2, v3 int = 2, 3 // `:=` funciona somente em funções // `:=` é a maneira curta de declarar variáveis sem // especificar o tipo e usando a palvra-chave `var`. vname1, vname2, vname3 := v1, v2, v3 // `_` desconsidera o valor retornado. _, b := 34, 35 fmt.Printf("vname1 = %v, vname2 = %v, vname3 = %v\n", vname1, vname2, vname3) fmt.Printf("v1 = %v, v2 = %v, v3 = %v\n", v1, v2, v3) fmt.Println("b =", b) } func show_bool() { fmt.Println("show_bool()") var available bool // variável local valid := false // declara a variável e infere o tipo booleano (declaração curta) available = true // atribui um valor a variável fmt.Printf("valid = %v, !valid = %v\n", valid, !valid) fmt.Printf("available = %v\n", available) } func show_different_types() { fmt.Println("show_different_types()") var ( unicodeChar rune a int8 b int16 c int32 d int64 e byte f uint8 g int16 h uint32 i uint64 ) var cmplx complex64 = 5 + 5i fmt.Println("Default values for int types") fmt.Println(unicodeChar, a, b, c, d, e, f, g, h, i) fmt.Printf("Value is: %v\n", cmplx) } func show_strings() { fmt.Println("show_strings()") no, yes, maybe := "no", "yes", "maybe" // declaração curta japaneseHello := "Ohaiyou" frenchHello = "Bonjour" // forma básica de atribuir valores fmt.Println("Random strings") fmt.Println(frenchHello, japaneseHello, no, yes, maybe) // A crase, `, não deixa escapar qualquer caractere da string fmt.Println(`This is on multiple lines`) } func show_string_manipulation() { fmt.Println("show_string_manipulation()") var s string = "hello" //Você não pode fazer isso com strings //s[0] = 'c' s = "hello" c := []byte(s) // converte string para o tipo []byte c[0] = 'c' s2 := string(c) // converte novamente para o tipo string m := " world" a := s + m d := "c" + s[1:] // você não pode alterar valores de string pelo índice, mas você pode obter os valores desta maneira fmt.Printf("%s\n", d) fmt.Printf("s = %s, c = %v\n", s, c) fmt.Printf("s2 = %s\n", s2) fmt.Printf("combined strings\na = %s, d = %s\n", a, d) } func show_errors() { fmt.Println("show_errors()") err := errors.New("Example error message\n") if err != nil { fmt.Print(err) } } func show_iota() { fmt.Println("show_iota()") const ( x = iota // x == 0 y = iota // y == 1 z = iota // z == 2 w // Se não houver nenhuma expressão após o nome da constante, // ela usa a última expressão, ou seja, neste caso w = iota implicitamente. // Portanto w == 3, e tanto y quanto z podem omitir "= iota" também. ) const v = iota // uma vez que iota encontra a palavra-chave `const`, ela é redefinida para `0`, então v = 0. const ( e, f, g = iota, iota, iota // e=0,f=0,g=0 valores de iota são iguais quando estão na mesma linha. ) fmt.Printf("x = %v, y = %v, z = %v, w = %v\n", x, y, z, w) fmt.Printf("v = %v\n", v) fmt.Printf("e = %v, f = %v, g = %v\n", e, f, g) } // Funções e variáveis começando com uma letra maiúscula são públicas para outros pacotes. // Todo o resto é privado. func This_is_public() {} func this_is_private() {} func set_default_values() { // valores padrão para os tipos. const ( a int = 0 b int8 = 0 c int32 = 0 d int64 = 0 e uint = 0x0 f rune = 0 // o tipo real de rune é int32 g byte = 0x0 // o tipo real de byte é uint8 h float32 = 0 // comprimento é 4 bytes i float64 = 0 // comprimento é 8 bytes j bool = false k string = "" ) } func show_arrays() { fmt.Println("show_arrays()") var arr [10]int // um array do tipo int arr[0] = 42 // array é baseado em 0 arr[1] = 13 // atribui valor ao elemento a := [3]int{1, 2, 3} // define um array do tipo int com 3 elementos b := [10]int{1, 2, 3} // define um array do tipo int com 10 elementos, // e os três primeiros são atribuídos, o restante usa o valor padrão 0. c := [...]int{4, 5, 6} // usa `…` para substituir o número do comprimento, Go irá calcular isto para você. // define um array bidimensional com 2 elementos, e onde cada elemento possui 4 elementos. doubleArray := [2][4]int{[4]int{1, 2, 3, 4}, [4]int{5, 6, 7, 8}} // Você pode escrever a declaração de forma curta. easyArray := [2][4]int{{1, 2, 3, 4}, {5, 6, 7, 8}} fmt.Println("arr =", arr) fmt.Printf("The first element is %d\n", arr[0]) // obtém o valor do elemento, retorna 42 fmt.Printf("The last element is %d\n", arr[9]) // retorna o valor padrão do décimo elemento do array, que neste caso é 0. fmt.Println("array a =", a) fmt.Println("array b =", b) fmt.Println("array c =", c) fmt.Println("array doubleArray =", doubleArray) fmt.Println("array easyArray =", easyArray) } func show_slices() { fmt.Println("show_slices()") // define um slice de tipo byte com 10 elementos var ar = [10]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'} // define dois slices com o tipo []byte var a, b []byte // a aponta para os elementos da posição 3 até a 5 do array ar. a = ar[2:5] // agora a possui os elementos ar[2], ar[3] e ar[4] // b é outro slice do array ar b = ar[3:5] // agora b possui os elementos de ar[3] e ar[4] // define um array var array = [10]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'} // define dois slices var aSlice, bSlice []byte // algumas operações convenientes aSlice = array[:3] // igual a aSlice = array[0:3] aSlice possui os elementos a,b,c aSlice = array[5:] // igual a aSlice = array[5:10] aSlice possui os elementos f,g,h,i,j aSlice = array[:] // igual a aSlice = array[0:10] aSlice possui todos os elementos // slice de slice aSlice = array[3:7] // aSlice possui os elementos d,e,f,g,len=4,cap=7 bSlice = aSlice[1:3] // bSlice contém aSlice[1], aSlice[2], ou seja, ele possui os elementos e,f bSlice = aSlice[:3] // bSlice contém aSlice[0], aSlice[1], aSlice[2], ou seja, ele possui os elementos d,e,f bSlice = aSlice[0:5] // bSlice pode ser expandido de acordo com cap, agora bSlice contém d,e,f,g,h bSlice = aSlice[:] // bSlice possui os mesmos elementos de aSlice, os quais são d,e,f,g fmt.Println("slice ar =", ar) fmt.Println("slice a =", a) fmt.Println("slice b =", b) fmt.Println("array =", array) fmt.Println("slice aSlice =", aSlice) fmt.Println("slice bSlice =", bSlice) fmt.Println("len(bSlice) =", len(bSlice)) } func show_map() { fmt.Println("show_map()") // use tipo string para a chave, tipo int para o valor, e você precisa usar `make` para inicializar var numbers map[string]int // outra forma de declarar map numbers = make(map[string]int) numbers["one"] = 1 // atribui valor pela chave numbers["ten"] = 10 numbers["three"] = 3 // Inicializa um map rating := map[string]float32{"C": 5, "Go": 4.5, "Python": 4.5, "C++": 2} fmt.Println("map numbers =", numbers) fmt.Println("The third number is: ", numbers["three"]) // obtém os valores // Isto irá imprimir: The third number is: 3 // map possui dois valores de retorno. Se a chave não existir, o segundo valor, neste caso "ok", será falso (false). Caso contrário será verdadeiro (true). csharpRating, ok := rating["C#"] if ok { fmt.Println("C# is in the map and its rating is ", csharpRating) } else { fmt.Println("We have no rating associated with C# in the map") } delete(rating, "C") // deleta o elemento com a chave "c" fmt.Printf("map rating = %#v\n", rating) } func main() { show_multiple_assignments() show_bool() show_different_types() show_strings() show_string_manipulation() show_errors() show_iota() set_default_values() show_arrays() show_slices() show_map() }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.2/what_is_wrong_with_this/main.go
pt-br/code/src/apps/ch.2.2/what_is_wrong_with_this/main.go
// Código de exemplo para o Capítulo 2.2 do "Build Web Application with Golang" // Propósito: Tente corrigir este programa. // No console, digite `go run main.go` package main func main() { var i int }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.4/main.go
pt-br/code/src/apps/ch.2.4/main.go
// Código de exemplo da seção 2.4 de "Build Web Application with Golang" // Propósito: Mostrar formas diferentes de criar uma estrutura package main import "fmt" func show_basic_struct() { fmt.Println("\nshow_basic_struct()") type person struct { name string age int } var P person // p é do tipo person P.name = "Astaxie" // atribui "Astaxie" ao campo 'name' de p P.age = 25 // atribui 25 ao campo 'age' de p fmt.Printf("The person's name is %s\n", P.name) // acessa o campo 'name' de p tom := person{"Tom", 25} bob := person{age: 24, name: "Bob"} fmt.Printf("tom = %+v\n", tom) fmt.Printf("bob = %#v\n", bob) } func show_anonymous_struct() { fmt.Println("\nshow_anonymous_struct()") fmt.Printf("Anonymous struct = %#v\n", struct { name string count int }{ "counter", 1, }) } func main() { show_basic_struct() show_anonymous_struct() }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.4/embedded_structs_with_name_conflict/main.go
pt-br/code/src/apps/ch.2.4/embedded_structs_with_name_conflict/main.go
// Código de exemplo da seção 2.4 de "Build Web Application with Golang" // Propósito: Mostra um conflito de nomes com um campo incorporado package main import "fmt" type Human struct { name string age int phone string // Human possui campo phone } type Employee struct { Human // campo incorporado de Human speciality string phone string // phone em employee } func main() { Bob := Employee{Human{"Bob", 34, "777-444-XXXX"}, "Designer", "333-222"} fmt.Println("Bob's work phone is:", Bob.phone) // acessa o campo phone em Human fmt.Println("Bob's personal phone is:", Bob.Human.phone) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.4/embedded_structs/main.go
pt-br/code/src/apps/ch.2.4/embedded_structs/main.go
// Código de exemplo da seção 2.4 de "Build Web Application with Golang" // Propósito: Exemplo de campos incorporados package main import "fmt" type Human struct { name string age int weight int } type Student struct { Human // campo anônimo, significa que a estrutura Student inclui todos os campos que Human possui. speciality string } func main() { // inicializa um estudante mark := Student{Human{"Mark", 25, 120}, "Computer Science"} // acessa os campos fmt.Println("His name is ", mark.name) fmt.Println("His age is ", mark.age) fmt.Println("His weight is ", mark.weight) fmt.Println("His speciality is ", mark.speciality) // modifica especialidade mark.speciality = "AI" fmt.Println("Mark changed his speciality") fmt.Println("His speciality is ", mark.speciality) // modifica idade fmt.Println("Mark become old") mark.age = 46 fmt.Println("His age is", mark.age) // modifica peso fmt.Println("Mark is not an athlete any more") mark.weight += 60 fmt.Println("His weight is", mark.weight) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.4/compare_age/main.go
pt-br/code/src/apps/ch.2.4/compare_age/main.go
// Código de exemplo da seção 2.4 de "Build Web Application with Golang" // Propósito: Mostrar como utilizar estruturas em Go. package main import "fmt" // define um novo tipo type person struct { name string age int } // compara a idade de duas pessoas e retorna dois valores: a pessoa mais velha e a diferença de idade // estrutura é passada por valor func Older(p1, p2 person) (person, int) { if p1.age > p2.age { return p1, p1.age - p2.age } return p2, p2.age - p1.age } func main() { var tom person // inicialização tom.name, tom.age = "Tom", 18 // inicializa dois valores pelo formato "campo:valor" bob := person{age: 25, name: "Bob"} // inicializa dois valores em ordem paul := person{"Paul", 43} tb_Older, tb_diff := Older(tom, bob) tp_Older, tp_diff := Older(tom, paul) bp_Older, bp_diff := Older(bob, paul) fmt.Printf("Of %s and %s, %s is older by %d years\n", tom.name, bob.name, tb_Older.name, tb_diff) fmt.Printf("Of %s and %s, %s is older by %d years\n", tom.name, paul.name, tp_Older.name, tp_diff) fmt.Printf("Of %s and %s, %s is older by %d years\n", bob.name, paul.name, bp_Older.name, bp_diff) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/apps/ch.2.4/embedded_structs2/main.go
pt-br/code/src/apps/ch.2.4/embedded_structs2/main.go
// Código de exemplo da seção 2.4 de "Build Web Application with Golang" // Propósito: Outro exemplo de campos incorporados package main import "fmt" type Skills []string type Human struct { name string age int weight int } type Student struct { Human // estrutura como campo incorporado Skills // string slice como campo incorporado int // tipo embutido como campo incorporado speciality string } func main() { // inicializa Student Jane jane := Student{Human: Human{"Jane", 35, 100}, speciality: "Biology"} // acessa os campos fmt.Println("Her name is ", jane.name) fmt.Println("Her age is ", jane.age) fmt.Println("Her weight is ", jane.weight) fmt.Println("Her speciality is ", jane.speciality) // modifica o valor do campo skill jane.Skills = []string{"anatomy"} fmt.Println("Her skills are ", jane.Skills) fmt.Println("She acquired two new ones ") jane.Skills = append(jane.Skills, "physics", "golang") fmt.Println("Her skills now are ", jane.Skills) // modifica campo incorporado jane.int = 3 fmt.Println("Her preferred number is", jane.int) }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/c294b087b96d99d2593ad8f470151af5354bb57f/pt-br/code/src/mymath/sqrt.go
pt-br/code/src/mymath/sqrt.go
// Example code for Chapter 1.2 from "Build Web Application with Golang" // Purpose: Shows how to create a simple package called `mymath` // This package must be imported from another go file to run. package mymath func Sqrt(x float64) float64 { z := 0.0 for i := 0; i < 1000; i++ { z -= (z*z - x) / (2 * x) } return z }
go
BSD-3-Clause
c294b087b96d99d2593ad8f470151af5354bb57f
2026-01-07T08:35:46.175972Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/key_other.go
key_other.go
//go:build !windows // +build !windows package tea import ( "context" "io" ) func readInputs(ctx context.Context, msgs chan<- Msg, input io.Reader) error { return readAnsiInputs(ctx, msgs, input) }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/exec.go
exec.go
package tea import ( "io" "os" "os/exec" ) // execMsg is used internally to run an ExecCommand sent with Exec. type execMsg struct { cmd ExecCommand fn ExecCallback } // Exec is used to perform arbitrary I/O in a blocking fashion, effectively // pausing the Program while execution is running and resuming it when // execution has completed. // // Most of the time you'll want to use ExecProcess, which runs an exec.Cmd. // // For non-interactive i/o you should use a Cmd (that is, a tea.Cmd). func Exec(c ExecCommand, fn ExecCallback) Cmd { return func() Msg { return execMsg{cmd: c, fn: fn} } } // ExecProcess runs the given *exec.Cmd in a blocking fashion, effectively // pausing the Program while the command is running. After the *exec.Cmd exists // the Program resumes. It's useful for spawning other interactive applications // such as editors and shells from within a Program. // // To produce the command, pass an *exec.Cmd and a function which returns // a message containing the error which may have occurred when running the // ExecCommand. // // type VimFinishedMsg struct { err error } // // c := exec.Command("vim", "file.txt") // // cmd := ExecProcess(c, func(err error) Msg { // return VimFinishedMsg{err: err} // }) // // Or, if you don't care about errors, you could simply: // // cmd := ExecProcess(exec.Command("vim", "file.txt"), nil) // // For non-interactive i/o you should use a Cmd (that is, a tea.Cmd). func ExecProcess(c *exec.Cmd, fn ExecCallback) Cmd { return Exec(wrapExecCommand(c), fn) } // ExecCallback is used when executing an *exec.Command to return a message // with an error, which may or may not be nil. type ExecCallback func(error) Msg // ExecCommand can be implemented to execute things in a blocking fashion in // the current terminal. type ExecCommand interface { Run() error SetStdin(io.Reader) SetStdout(io.Writer) SetStderr(io.Writer) } // wrapExecCommand wraps an exec.Cmd so that it satisfies the ExecCommand // interface so it can be used with Exec. func wrapExecCommand(c *exec.Cmd) ExecCommand { return &osExecCommand{Cmd: c} } // osExecCommand is a layer over an exec.Cmd that satisfies the ExecCommand // interface. type osExecCommand struct{ *exec.Cmd } // SetStdin sets stdin on underlying exec.Cmd to the given io.Reader. func (c *osExecCommand) SetStdin(r io.Reader) { // If unset, have the command use the same input as the terminal. if c.Stdin == nil { c.Stdin = r } } // SetStdout sets stdout on underlying exec.Cmd to the given io.Writer. func (c *osExecCommand) SetStdout(w io.Writer) { // If unset, have the command use the same output as the terminal. if c.Stdout == nil { c.Stdout = w } } // SetStderr sets stderr on the underlying exec.Cmd to the given io.Writer. func (c *osExecCommand) SetStderr(w io.Writer) { // If unset, use stderr for the command's stderr if c.Stderr == nil { c.Stderr = w } } // exec runs an ExecCommand and delivers the results to the program as a Msg. func (p *Program) exec(c ExecCommand, fn ExecCallback) { if err := p.ReleaseTerminal(); err != nil { // If we can't release input, abort. if fn != nil { go p.Send(fn(err)) } return } c.SetStdin(p.input) c.SetStdout(p.output) c.SetStderr(os.Stderr) // Execute system command. if err := c.Run(); err != nil { p.renderer.resetLinesRendered() _ = p.RestoreTerminal() // also try to restore the terminal. if fn != nil { go p.Send(fn(err)) } return } // Maintain the existing output from the command p.renderer.resetLinesRendered() // Have the program re-capture input. err := p.RestoreTerminal() if fn != nil { go p.Send(fn(err)) } }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/nil_renderer.go
nil_renderer.go
package tea type nilRenderer struct{} func (n nilRenderer) start() {} func (n nilRenderer) stop() {} func (n nilRenderer) kill() {} func (n nilRenderer) write(_ string) {} func (n nilRenderer) repaint() {} func (n nilRenderer) clearScreen() {} func (n nilRenderer) altScreen() bool { return false } func (n nilRenderer) enterAltScreen() {} func (n nilRenderer) exitAltScreen() {} func (n nilRenderer) showCursor() {} func (n nilRenderer) hideCursor() {} func (n nilRenderer) enableMouseCellMotion() {} func (n nilRenderer) disableMouseCellMotion() {} func (n nilRenderer) enableMouseAllMotion() {} func (n nilRenderer) disableMouseAllMotion() {} func (n nilRenderer) enableBracketedPaste() {} func (n nilRenderer) disableBracketedPaste() {} func (n nilRenderer) enableMouseSGRMode() {} func (n nilRenderer) disableMouseSGRMode() {} func (n nilRenderer) bracketedPasteActive() bool { return false } func (n nilRenderer) setWindowTitle(_ string) {} func (n nilRenderer) reportFocus() bool { return false } func (n nilRenderer) enableReportFocus() {} func (n nilRenderer) disableReportFocus() {} func (n nilRenderer) resetLinesRendered() {}
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/mouse.go
mouse.go
package tea import "strconv" // MouseMsg contains information about a mouse event and are sent to a programs // update function when mouse activity occurs. Note that the mouse must first // be enabled in order for the mouse events to be received. type MouseMsg MouseEvent // String returns a string representation of a mouse event. func (m MouseMsg) String() string { return MouseEvent(m).String() } // MouseEvent represents a mouse event, which could be a click, a scroll wheel // movement, a cursor movement, or a combination. type MouseEvent struct { X int Y int Shift bool Alt bool Ctrl bool Action MouseAction Button MouseButton // Deprecated: Use MouseAction & MouseButton instead. Type MouseEventType } // IsWheel returns true if the mouse event is a wheel event. func (m MouseEvent) IsWheel() bool { return m.Button == MouseButtonWheelUp || m.Button == MouseButtonWheelDown || m.Button == MouseButtonWheelLeft || m.Button == MouseButtonWheelRight } // String returns a string representation of a mouse event. func (m MouseEvent) String() (s string) { if m.Ctrl { s += "ctrl+" } if m.Alt { s += "alt+" } if m.Shift { s += "shift+" } if m.Button == MouseButtonNone { //nolint:nestif if m.Action == MouseActionMotion || m.Action == MouseActionRelease { s += mouseActions[m.Action] } else { s += "unknown" } } else if m.IsWheel() { s += mouseButtons[m.Button] } else { btn := mouseButtons[m.Button] if btn != "" { s += btn } act := mouseActions[m.Action] if act != "" { s += " " + act } } return s } // MouseAction represents the action that occurred during a mouse event. type MouseAction int // Mouse event actions. const ( MouseActionPress MouseAction = iota MouseActionRelease MouseActionMotion ) var mouseActions = map[MouseAction]string{ MouseActionPress: "press", MouseActionRelease: "release", MouseActionMotion: "motion", } // MouseButton represents the button that was pressed during a mouse event. type MouseButton int // Mouse event buttons // // This is based on X11 mouse button codes. // // 1 = left button // 2 = middle button (pressing the scroll wheel) // 3 = right button // 4 = turn scroll wheel up // 5 = turn scroll wheel down // 6 = push scroll wheel left // 7 = push scroll wheel right // 8 = 4th button (aka browser backward button) // 9 = 5th button (aka browser forward button) // 10 // 11 // // Other buttons are not supported. const ( MouseButtonNone MouseButton = iota MouseButtonLeft MouseButtonMiddle MouseButtonRight MouseButtonWheelUp MouseButtonWheelDown MouseButtonWheelLeft MouseButtonWheelRight MouseButtonBackward MouseButtonForward MouseButton10 MouseButton11 ) var mouseButtons = map[MouseButton]string{ MouseButtonNone: "none", MouseButtonLeft: "left", MouseButtonMiddle: "middle", MouseButtonRight: "right", MouseButtonWheelUp: "wheel up", MouseButtonWheelDown: "wheel down", MouseButtonWheelLeft: "wheel left", MouseButtonWheelRight: "wheel right", MouseButtonBackward: "backward", MouseButtonForward: "forward", MouseButton10: "button 10", MouseButton11: "button 11", } // MouseEventType indicates the type of mouse event occurring. // // Deprecated: Use MouseAction & MouseButton instead. type MouseEventType int // Mouse event types. // // Deprecated: Use MouseAction & MouseButton instead. const ( MouseUnknown MouseEventType = iota MouseLeft MouseRight MouseMiddle MouseRelease // mouse button release (X10 only) MouseWheelUp MouseWheelDown MouseWheelLeft MouseWheelRight MouseBackward MouseForward MouseMotion ) // Parse SGR-encoded mouse events; SGR extended mouse events. SGR mouse events // look like: // // ESC [ < Cb ; Cx ; Cy (M or m) // // where: // // Cb is the encoded button code // Cx is the x-coordinate of the mouse // Cy is the y-coordinate of the mouse // M is for button press, m is for button release // // https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Extended-coordinates func parseSGRMouseEvent(buf []byte) MouseEvent { str := string(buf[3:]) matches := mouseSGRRegex.FindStringSubmatch(str) if len(matches) != 5 { //nolint:mnd // Unreachable, we already checked the regex in `detectOneMsg`. panic("invalid mouse event") } b, _ := strconv.Atoi(matches[1]) px := matches[2] py := matches[3] release := matches[4] == "m" m := parseMouseButton(b, true) // Wheel buttons don't have release events // Motion can be reported as a release event in some terminals (Windows Terminal) if m.Action != MouseActionMotion && !m.IsWheel() && release { m.Action = MouseActionRelease m.Type = MouseRelease } x, _ := strconv.Atoi(px) y, _ := strconv.Atoi(py) // (1,1) is the upper left. We subtract 1 to normalize it to (0,0). m.X = x - 1 m.Y = y - 1 return m } const x10MouseByteOffset = 32 // Parse X10-encoded mouse events; the simplest kind. The last release of X10 // was December 1986, by the way. The original X10 mouse protocol limits the Cx // and Cy coordinates to 223 (=255-032). // // X10 mouse events look like: // // ESC [M Cb Cx Cy // // See: http://www.xfree86.org/current/ctlseqs.html#Mouse%20Tracking func parseX10MouseEvent(buf []byte) MouseEvent { v := buf[3:6] m := parseMouseButton(int(v[0]), false) // (1,1) is the upper left. We subtract 1 to normalize it to (0,0). m.X = int(v[1]) - x10MouseByteOffset - 1 m.Y = int(v[2]) - x10MouseByteOffset - 1 return m } // See: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Extended-coordinates func parseMouseButton(b int, isSGR bool) MouseEvent { var m MouseEvent e := b if !isSGR { e -= x10MouseByteOffset } const ( bitShift = 0b0000_0100 bitAlt = 0b0000_1000 bitCtrl = 0b0001_0000 bitMotion = 0b0010_0000 bitWheel = 0b0100_0000 bitAdd = 0b1000_0000 // additional buttons 8-11 bitsMask = 0b0000_0011 ) if e&bitAdd != 0 { m.Button = MouseButtonBackward + MouseButton(e&bitsMask) } else if e&bitWheel != 0 { m.Button = MouseButtonWheelUp + MouseButton(e&bitsMask) } else { m.Button = MouseButtonLeft + MouseButton(e&bitsMask) // X10 reports a button release as 0b0000_0011 (3) if e&bitsMask == bitsMask { m.Action = MouseActionRelease m.Button = MouseButtonNone } } // Motion bit doesn't get reported for wheel events. if e&bitMotion != 0 && !m.IsWheel() { m.Action = MouseActionMotion } // Modifiers m.Alt = e&bitAlt != 0 m.Ctrl = e&bitCtrl != 0 m.Shift = e&bitShift != 0 // backward compatibility switch { case m.Button == MouseButtonLeft && m.Action == MouseActionPress: m.Type = MouseLeft case m.Button == MouseButtonMiddle && m.Action == MouseActionPress: m.Type = MouseMiddle case m.Button == MouseButtonRight && m.Action == MouseActionPress: m.Type = MouseRight case m.Button == MouseButtonNone && m.Action == MouseActionRelease: m.Type = MouseRelease case m.Button == MouseButtonWheelUp && m.Action == MouseActionPress: m.Type = MouseWheelUp case m.Button == MouseButtonWheelDown && m.Action == MouseActionPress: m.Type = MouseWheelDown case m.Button == MouseButtonWheelLeft && m.Action == MouseActionPress: m.Type = MouseWheelLeft case m.Button == MouseButtonWheelRight && m.Action == MouseActionPress: m.Type = MouseWheelRight case m.Button == MouseButtonBackward && m.Action == MouseActionPress: m.Type = MouseBackward case m.Button == MouseButtonForward && m.Action == MouseActionPress: m.Type = MouseForward case m.Action == MouseActionMotion: m.Type = MouseMotion switch m.Button { //nolint:exhaustive case MouseButtonLeft: m.Type = MouseLeft case MouseButtonMiddle: m.Type = MouseMiddle case MouseButtonRight: m.Type = MouseRight case MouseButtonBackward: m.Type = MouseBackward case MouseButtonForward: m.Type = MouseForward } default: m.Type = MouseUnknown } return m }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/tea_test.go
tea_test.go
package tea import ( "bytes" "context" "errors" "sync" "sync/atomic" "testing" "time" ) type ctxImplodeMsg struct { cancel context.CancelFunc } type incrementMsg struct{} type panicMsg struct{} func panicCmd() Msg { panic("testing goroutine panic behavior") } type testModel struct { executed atomic.Value counter atomic.Value } func (m testModel) Init() Cmd { return nil } func (m *testModel) Update(msg Msg) (Model, Cmd) { switch msg := msg.(type) { case ctxImplodeMsg: msg.cancel() time.Sleep(100 * time.Millisecond) case incrementMsg: i := m.counter.Load() if i == nil { m.counter.Store(1) } else { m.counter.Store(i.(int) + 1) } case KeyMsg: return m, Quit case panicMsg: panic("testing panic behavior") } return m, nil } func (m *testModel) View() string { m.executed.Store(true) return "success\n" } func TestTeaModel(t *testing.T) { var buf bytes.Buffer var in bytes.Buffer in.Write([]byte("q")) ctx, cancel := context.WithTimeout(context.TODO(), 3*time.Second) defer cancel() p := NewProgram(&testModel{}, WithInput(&in), WithOutput(&buf), WithContext(ctx)) if _, err := p.Run(); err != nil { t.Fatal(err) } if buf.Len() == 0 { t.Fatal("no output") } } func TestTeaQuit(t *testing.T) { var buf bytes.Buffer var in bytes.Buffer m := &testModel{} p := NewProgram(m, WithInput(&in), WithOutput(&buf)) go func() { for { time.Sleep(time.Millisecond) if m.executed.Load() != nil { p.Quit() return } } }() if _, err := p.Run(); err != nil { t.Fatal(err) } } func TestTeaWaitQuit(t *testing.T) { var buf bytes.Buffer var in bytes.Buffer progStarted := make(chan struct{}) waitStarted := make(chan struct{}) errChan := make(chan error, 1) m := &testModel{} p := NewProgram(m, WithInput(&in), WithOutput(&buf)) go func() { _, err := p.Run() errChan <- err }() go func() { for { time.Sleep(time.Millisecond) if m.executed.Load() != nil { close(progStarted) <-waitStarted time.Sleep(50 * time.Millisecond) p.Quit() return } } }() <-progStarted var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(1) go func() { p.Wait() wg.Done() }() } close(waitStarted) wg.Wait() err := <-errChan if err != nil { t.Fatalf("Expected nil, got %v", err) } } func TestTeaWaitKill(t *testing.T) { var buf bytes.Buffer var in bytes.Buffer progStarted := make(chan struct{}) waitStarted := make(chan struct{}) errChan := make(chan error, 1) m := &testModel{} p := NewProgram(m, WithInput(&in), WithOutput(&buf)) go func() { _, err := p.Run() errChan <- err }() go func() { for { time.Sleep(time.Millisecond) if m.executed.Load() != nil { close(progStarted) <-waitStarted time.Sleep(50 * time.Millisecond) p.Kill() return } } }() <-progStarted var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(1) go func() { p.Wait() wg.Done() }() } close(waitStarted) wg.Wait() err := <-errChan if !errors.Is(err, ErrProgramKilled) { t.Fatalf("Expected %v, got %v", ErrProgramKilled, err) } } func TestTeaWithFilter(t *testing.T) { testTeaWithFilter(t, 0) testTeaWithFilter(t, 1) testTeaWithFilter(t, 2) } func testTeaWithFilter(t *testing.T, preventCount uint32) { var buf bytes.Buffer var in bytes.Buffer m := &testModel{} shutdowns := uint32(0) p := NewProgram(m, WithInput(&in), WithOutput(&buf), WithFilter(func(_ Model, msg Msg) Msg { if _, ok := msg.(QuitMsg); !ok { return msg } if shutdowns < preventCount { atomic.AddUint32(&shutdowns, 1) return nil } return msg })) go func() { for atomic.LoadUint32(&shutdowns) <= preventCount { time.Sleep(time.Millisecond) p.Quit() } }() if err := p.Start(); err != nil { t.Fatal(err) } if shutdowns != preventCount { t.Errorf("Expected %d prevented shutdowns, got %d", preventCount, shutdowns) } } func TestTeaKill(t *testing.T) { var buf bytes.Buffer var in bytes.Buffer m := &testModel{} p := NewProgram(m, WithInput(&in), WithOutput(&buf)) go func() { for { time.Sleep(time.Millisecond) if m.executed.Load() != nil { p.Kill() return } } }() _, err := p.Run() if !errors.Is(err, ErrProgramKilled) { t.Fatalf("Expected %v, got %v", ErrProgramKilled, err) } if errors.Is(err, context.Canceled) { // The end user should not know about the program's internal context state. // The program should only report external context cancellation as a context error. t.Fatalf("Internal context cancellation was reported as context error!") } } func TestTeaContext(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) var buf bytes.Buffer var in bytes.Buffer m := &testModel{} p := NewProgram(m, WithContext(ctx), WithInput(&in), WithOutput(&buf)) go func() { for { time.Sleep(time.Millisecond) if m.executed.Load() != nil { cancel() return } } }() _, err := p.Run() if !errors.Is(err, ErrProgramKilled) { t.Fatalf("Expected %v, got %v", ErrProgramKilled, err) } if !errors.Is(err, context.Canceled) { // The end user should know that their passed in context caused the kill. t.Fatalf("Expected %v, got %v", context.Canceled, err) } } func TestTeaContextImplodeDeadlock(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) var buf bytes.Buffer var in bytes.Buffer m := &testModel{} p := NewProgram(m, WithContext(ctx), WithInput(&in), WithOutput(&buf)) go func() { for { time.Sleep(time.Millisecond) if m.executed.Load() != nil { p.Send(ctxImplodeMsg{cancel: cancel}) return } } }() if _, err := p.Run(); !errors.Is(err, ErrProgramKilled) { t.Fatalf("Expected %v, got %v", ErrProgramKilled, err) } } func TestTeaContextBatchDeadlock(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) var buf bytes.Buffer var in bytes.Buffer inc := func() Msg { cancel() return incrementMsg{} } m := &testModel{} p := NewProgram(m, WithContext(ctx), WithInput(&in), WithOutput(&buf)) go func() { for { time.Sleep(time.Millisecond) if m.executed.Load() != nil { batch := make(BatchMsg, 100) for i := range batch { batch[i] = inc } p.Send(batch) return } } }() if _, err := p.Run(); !errors.Is(err, ErrProgramKilled) { t.Fatalf("Expected %v, got %v", ErrProgramKilled, err) } } func TestTeaBatchMsg(t *testing.T) { var buf bytes.Buffer var in bytes.Buffer inc := func() Msg { return incrementMsg{} } m := &testModel{} p := NewProgram(m, WithInput(&in), WithOutput(&buf)) go func() { p.Send(BatchMsg{inc, inc}) for { time.Sleep(time.Millisecond) i := m.counter.Load() if i != nil && i.(int) >= 2 { p.Quit() return } } }() if _, err := p.Run(); err != nil { t.Fatal(err) } if m.counter.Load() != 2 { t.Fatalf("counter should be 2, got %d", m.counter.Load()) } } func TestTeaSequenceMsg(t *testing.T) { var buf bytes.Buffer var in bytes.Buffer inc := func() Msg { return incrementMsg{} } m := &testModel{} p := NewProgram(m, WithInput(&in), WithOutput(&buf)) go p.Send(sequenceMsg{inc, inc, Quit}) if _, err := p.Run(); err != nil { t.Fatal(err) } if m.counter.Load() != 2 { t.Fatalf("counter should be 2, got %d", m.counter.Load()) } } func TestTeaSequenceMsgWithBatchMsg(t *testing.T) { var buf bytes.Buffer var in bytes.Buffer inc := func() Msg { return incrementMsg{} } batch := func() Msg { return BatchMsg{inc, inc} } m := &testModel{} p := NewProgram(m, WithInput(&in), WithOutput(&buf)) go p.Send(sequenceMsg{batch, inc, Quit}) if _, err := p.Run(); err != nil { t.Fatal(err) } if m.counter.Load() != 3 { t.Fatalf("counter should be 3, got %d", m.counter.Load()) } } func TestTeaNestedSequenceMsg(t *testing.T) { var buf bytes.Buffer var in bytes.Buffer inc := func() Msg { return incrementMsg{} } m := &testModel{} p := NewProgram(m, WithInput(&in), WithOutput(&buf)) go p.Send(sequenceMsg{inc, Sequence(inc, inc, Batch(inc, inc)), Quit}) if _, err := p.Run(); err != nil { t.Fatal(err) } if m.counter.Load() != 5 { t.Fatalf("counter should be 5, got %d", m.counter.Load()) } } func TestTeaSend(t *testing.T) { var buf bytes.Buffer var in bytes.Buffer m := &testModel{} p := NewProgram(m, WithInput(&in), WithOutput(&buf)) // sending before the program is started is a blocking operation go p.Send(Quit()) if _, err := p.Run(); err != nil { t.Fatal(err) } // sending a message after program has quit is a no-op p.Send(Quit()) } func TestTeaNoRun(t *testing.T) { var buf bytes.Buffer var in bytes.Buffer m := &testModel{} NewProgram(m, WithInput(&in), WithOutput(&buf)) } func TestTeaPanic(t *testing.T) { var buf bytes.Buffer var in bytes.Buffer m := &testModel{} p := NewProgram(m, WithInput(&in), WithOutput(&buf)) go func() { for { time.Sleep(time.Millisecond) if m.executed.Load() != nil { p.Send(panicMsg{}) return } } }() _, err := p.Run() if !errors.Is(err, ErrProgramPanic) { t.Fatalf("Expected %v, got %v", ErrProgramPanic, err) } if !errors.Is(err, ErrProgramKilled) { t.Fatalf("Expected %v, got %v", ErrProgramKilled, err) } } func TestTeaGoroutinePanic(t *testing.T) { var buf bytes.Buffer var in bytes.Buffer m := &testModel{} p := NewProgram(m, WithInput(&in), WithOutput(&buf)) go func() { for { time.Sleep(time.Millisecond) if m.executed.Load() != nil { batch := make(BatchMsg, 10) for i := 0; i < len(batch); i += 2 { batch[i] = Sequence(panicCmd) batch[i+1] = Batch(panicCmd) } p.Send(batch) return } } }() _, err := p.Run() if !errors.Is(err, ErrProgramPanic) { t.Fatalf("Expected %v, got %v", ErrProgramPanic, err) } if !errors.Is(err, ErrProgramKilled) { t.Fatalf("Expected %v, got %v", ErrProgramKilled, err) } }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/key_test.go
key_test.go
package tea import ( "bytes" "context" "errors" "flag" "fmt" "io" "math/rand" "reflect" "runtime" "sort" "strings" "sync" "testing" "time" ) func TestKeyString(t *testing.T) { t.Run("alt+space", func(t *testing.T) { if got := KeyMsg(Key{ Type: KeySpace, Alt: true, }).String(); got != "alt+ " { t.Fatalf(`expected a "alt+ ", got %q`, got) } }) t.Run("runes", func(t *testing.T) { if got := KeyMsg(Key{ Type: KeyRunes, Runes: []rune{'a'}, }).String(); got != "a" { t.Fatalf(`expected an "a", got %q`, got) } }) t.Run("invalid", func(t *testing.T) { if got := KeyMsg(Key{ Type: KeyType(99999), }).String(); got != "" { t.Fatalf(`expected a "", got %q`, got) } }) } func TestKeyTypeString(t *testing.T) { t.Run("space", func(t *testing.T) { if got := KeySpace.String(); got != " " { t.Fatalf(`expected a " ", got %q`, got) } }) t.Run("invalid", func(t *testing.T) { if got := KeyType(99999).String(); got != "" { t.Fatalf(`expected a "", got %q`, got) } }) } type seqTest struct { seq []byte msg Msg } // buildBaseSeqTests returns sequence tests that are valid for the // detectSequence() function. func buildBaseSeqTests() []seqTest { td := []seqTest{} for seq, key := range sequences { td = append(td, seqTest{[]byte(seq), KeyMsg(key)}) if !key.Alt { key.Alt = true td = append(td, seqTest{[]byte("\x1b" + seq), KeyMsg(key)}) } } // Add all the control characters. for i := keyNUL + 1; i <= keyDEL; i++ { if i == keyESC { // Not handled in detectSequence(), so not part of the base test // suite. continue } td = append(td, seqTest{[]byte{byte(i)}, KeyMsg{Type: i}}) td = append(td, seqTest{[]byte{'\x1b', byte(i)}, KeyMsg{Type: i, Alt: true}}) if i == keyUS { i = keyDEL - 1 } } // Additional special cases. td = append(td, // Unrecognized CSI sequence. seqTest{ []byte{'\x1b', '[', '-', '-', '-', '-', 'X'}, unknownCSISequenceMsg([]byte{'\x1b', '[', '-', '-', '-', '-', 'X'}), }, // A lone space character. seqTest{ []byte{' '}, KeyMsg{Type: KeySpace, Runes: []rune(" ")}, }, // An escape character with the alt modifier. seqTest{ []byte{'\x1b', ' '}, KeyMsg{Type: KeySpace, Runes: []rune(" "), Alt: true}, }, ) return td } func TestDetectSequence(t *testing.T) { td := buildBaseSeqTests() for _, tc := range td { t.Run(fmt.Sprintf("%q", string(tc.seq)), func(t *testing.T) { hasSeq, width, msg := detectSequence(tc.seq) if !hasSeq { t.Fatalf("no sequence found") } if width != len(tc.seq) { t.Errorf("parser did not consume the entire input: got %d, expected %d", width, len(tc.seq)) } if !reflect.DeepEqual(tc.msg, msg) { t.Errorf("expected event %#v (%T), got %#v (%T)", tc.msg, tc.msg, msg, msg) } }) } } func TestDetectOneMsg(t *testing.T) { td := buildBaseSeqTests() // Add tests for the inputs that detectOneMsg() can parse, but // detectSequence() cannot. td = append(td, // focus/blur seqTest{ []byte{'\x1b', '[', 'I'}, FocusMsg{}, }, seqTest{ []byte{'\x1b', '[', 'O'}, BlurMsg{}, }, // Mouse event. seqTest{ []byte{'\x1b', '[', 'M', byte(32) + 0b0100_0000, byte(65), byte(49)}, MouseMsg{X: 32, Y: 16, Type: MouseWheelUp, Button: MouseButtonWheelUp, Action: MouseActionPress}, }, // SGR Mouse event. seqTest{ []byte("\x1b[<0;33;17M"), MouseMsg{X: 32, Y: 16, Type: MouseLeft, Button: MouseButtonLeft, Action: MouseActionPress}, }, // Runes. seqTest{ []byte{'a'}, KeyMsg{Type: KeyRunes, Runes: []rune("a")}, }, seqTest{ []byte{'\x1b', 'a'}, KeyMsg{Type: KeyRunes, Runes: []rune("a"), Alt: true}, }, seqTest{ []byte{'a', 'a', 'a'}, KeyMsg{Type: KeyRunes, Runes: []rune("aaa")}, }, // Multi-byte rune. seqTest{ []byte("☃"), KeyMsg{Type: KeyRunes, Runes: []rune("☃")}, }, seqTest{ []byte("\x1b☃"), KeyMsg{Type: KeyRunes, Runes: []rune("☃"), Alt: true}, }, // Standalone control chacters. seqTest{ []byte{'\x1b'}, KeyMsg{Type: KeyEscape}, }, seqTest{ []byte{byte(keySOH)}, KeyMsg{Type: KeyCtrlA}, }, seqTest{ []byte{'\x1b', byte(keySOH)}, KeyMsg{Type: KeyCtrlA, Alt: true}, }, seqTest{ []byte{byte(keyNUL)}, KeyMsg{Type: KeyCtrlAt}, }, seqTest{ []byte{'\x1b', byte(keyNUL)}, KeyMsg{Type: KeyCtrlAt, Alt: true}, }, // Invalid characters. seqTest{ []byte{'\x80'}, unknownInputByteMsg(0x80), }, ) if runtime.GOOS != "windows" { // Sadly, utf8.DecodeRune([]byte(0xfe)) returns a valid rune on windows. // This is incorrect, but it makes our test fail if we try it out. td = append(td, seqTest{ []byte{'\xfe'}, unknownInputByteMsg(0xfe), }) } for _, tc := range td { t.Run(fmt.Sprintf("%q", string(tc.seq)), func(t *testing.T) { width, msg := detectOneMsg(tc.seq, false /* canHaveMoreData */) if width != len(tc.seq) { t.Errorf("parser did not consume the entire input: got %d, expected %d", width, len(tc.seq)) } if !reflect.DeepEqual(tc.msg, msg) { t.Errorf("expected event %#v (%T), got %#v (%T)", tc.msg, tc.msg, msg, msg) } }) } } func TestReadLongInput(t *testing.T) { input := strings.Repeat("a", 1000) msgs := testReadInputs(t, bytes.NewReader([]byte(input))) if len(msgs) != 1 { t.Errorf("expected 1 messages, got %d", len(msgs)) } km := msgs[0] k := Key(km.(KeyMsg)) if k.Type != KeyRunes { t.Errorf("expected key runes, got %d", k.Type) } if len(k.Runes) != 1000 || !reflect.DeepEqual(k.Runes, []rune(input)) { t.Errorf("unexpected runes: %+v", k) } if k.Alt { t.Errorf("unexpected alt") } } func TestReadInput(t *testing.T) { type test struct { keyname string in []byte out []Msg } testData := []test{ { "a", []byte{'a'}, []Msg{ KeyMsg{ Type: KeyRunes, Runes: []rune{'a'}, }, }, }, { " ", []byte{' '}, []Msg{ KeyMsg{ Type: KeySpace, Runes: []rune{' '}, }, }, }, { "a alt+a", []byte{'a', '\x1b', 'a'}, []Msg{ KeyMsg{Type: KeyRunes, Runes: []rune{'a'}}, KeyMsg{Type: KeyRunes, Runes: []rune{'a'}, Alt: true}, }, }, { "a alt+a a", []byte{'a', '\x1b', 'a', 'a'}, []Msg{ KeyMsg{Type: KeyRunes, Runes: []rune{'a'}}, KeyMsg{Type: KeyRunes, Runes: []rune{'a'}, Alt: true}, KeyMsg{Type: KeyRunes, Runes: []rune{'a'}}, }, }, { "ctrl+a", []byte{byte(keySOH)}, []Msg{ KeyMsg{ Type: KeyCtrlA, }, }, }, { "ctrl+a ctrl+b", []byte{byte(keySOH), byte(keySTX)}, []Msg{ KeyMsg{Type: KeyCtrlA}, KeyMsg{Type: KeyCtrlB}, }, }, { "alt+a", []byte{byte(0x1b), 'a'}, []Msg{ KeyMsg{ Type: KeyRunes, Alt: true, Runes: []rune{'a'}, }, }, }, { "abcd", []byte{'a', 'b', 'c', 'd'}, []Msg{ KeyMsg{ Type: KeyRunes, Runes: []rune{'a', 'b', 'c', 'd'}, }, }, }, { "up", []byte("\x1b[A"), []Msg{ KeyMsg{ Type: KeyUp, }, }, }, { "wheel up", []byte{'\x1b', '[', 'M', byte(32) + 0b0100_0000, byte(65), byte(49)}, []Msg{ MouseMsg{ X: 32, Y: 16, Type: MouseWheelUp, Button: MouseButtonWheelUp, Action: MouseActionPress, }, }, }, { "left motion release", []byte{ '\x1b', '[', 'M', byte(32) + 0b0010_0000, byte(32 + 33), byte(16 + 33), '\x1b', '[', 'M', byte(32) + 0b0000_0011, byte(64 + 33), byte(32 + 33), }, []Msg{ MouseMsg(MouseEvent{ X: 32, Y: 16, Type: MouseLeft, Button: MouseButtonLeft, Action: MouseActionMotion, }), MouseMsg(MouseEvent{ X: 64, Y: 32, Type: MouseRelease, Button: MouseButtonNone, Action: MouseActionRelease, }), }, }, { "shift+tab", []byte{'\x1b', '[', 'Z'}, []Msg{ KeyMsg{ Type: KeyShiftTab, }, }, }, { "enter", []byte{'\r'}, []Msg{KeyMsg{Type: KeyEnter}}, }, { "alt+enter", []byte{'\x1b', '\r'}, []Msg{ KeyMsg{ Type: KeyEnter, Alt: true, }, }, }, { "insert", []byte{'\x1b', '[', '2', '~'}, []Msg{ KeyMsg{ Type: KeyInsert, }, }, }, { "alt+ctrl+a", []byte{'\x1b', byte(keySOH)}, []Msg{ KeyMsg{ Type: KeyCtrlA, Alt: true, }, }, }, { "?CSI[45 45 45 45 88]?", []byte{'\x1b', '[', '-', '-', '-', '-', 'X'}, []Msg{unknownCSISequenceMsg([]byte{'\x1b', '[', '-', '-', '-', '-', 'X'})}, }, // Powershell sequences. { "up", []byte{'\x1b', 'O', 'A'}, []Msg{KeyMsg{Type: KeyUp}}, }, { "down", []byte{'\x1b', 'O', 'B'}, []Msg{KeyMsg{Type: KeyDown}}, }, { "right", []byte{'\x1b', 'O', 'C'}, []Msg{KeyMsg{Type: KeyRight}}, }, { "left", []byte{'\x1b', 'O', 'D'}, []Msg{KeyMsg{Type: KeyLeft}}, }, { "alt+enter", []byte{'\x1b', '\x0d'}, []Msg{KeyMsg{Type: KeyEnter, Alt: true}}, }, { "alt+backspace", []byte{'\x1b', '\x7f'}, []Msg{KeyMsg{Type: KeyBackspace, Alt: true}}, }, { "ctrl+@", []byte{'\x00'}, []Msg{KeyMsg{Type: KeyCtrlAt}}, }, { "alt+ctrl+@", []byte{'\x1b', '\x00'}, []Msg{KeyMsg{Type: KeyCtrlAt, Alt: true}}, }, { "esc", []byte{'\x1b'}, []Msg{KeyMsg{Type: KeyEsc}}, }, { "alt+esc", []byte{'\x1b', '\x1b'}, []Msg{KeyMsg{Type: KeyEsc, Alt: true}}, }, { "[a b] o", []byte{ '\x1b', '[', '2', '0', '0', '~', 'a', ' ', 'b', '\x1b', '[', '2', '0', '1', '~', 'o', }, []Msg{ KeyMsg{Type: KeyRunes, Runes: []rune("a b"), Paste: true}, KeyMsg{Type: KeyRunes, Runes: []rune("o")}, }, }, { "[a\x03\nb]", []byte{ '\x1b', '[', '2', '0', '0', '~', 'a', '\x03', '\n', 'b', '\x1b', '[', '2', '0', '1', '~', }, []Msg{ KeyMsg{Type: KeyRunes, Runes: []rune("a\x03\nb"), Paste: true}, }, }, } if runtime.GOOS != "windows" { // Sadly, utf8.DecodeRune([]byte(0xfe)) returns a valid rune on windows. // This is incorrect, but it makes our test fail if we try it out. testData = append(testData, test{ "?0xfe?", []byte{'\xfe'}, []Msg{unknownInputByteMsg(0xfe)}, }, test{ "a ?0xfe? b", []byte{'a', '\xfe', ' ', 'b'}, []Msg{ KeyMsg{Type: KeyRunes, Runes: []rune{'a'}}, unknownInputByteMsg(0xfe), KeyMsg{Type: KeySpace, Runes: []rune{' '}}, KeyMsg{Type: KeyRunes, Runes: []rune{'b'}}, }, }, ) } for i, td := range testData { t.Run(fmt.Sprintf("%d: %s", i, td.keyname), func(t *testing.T) { msgs := testReadInputs(t, bytes.NewReader(td.in)) var buf strings.Builder for i, msg := range msgs { if i > 0 { buf.WriteByte(' ') } if s, ok := msg.(fmt.Stringer); ok { buf.WriteString(s.String()) } else { fmt.Fprintf(&buf, "%#v:%T", msg, msg) } } title := buf.String() if title != td.keyname { t.Errorf("expected message titles:\n %s\ngot:\n %s", td.keyname, title) } if len(msgs) != len(td.out) { t.Fatalf("unexpected message list length: got %d, expected %d\n%#v", len(msgs), len(td.out), msgs) } if !reflect.DeepEqual(td.out, msgs) { t.Fatalf("expected:\n%#v\ngot:\n%#v", td.out, msgs) } }) } } func testReadInputs(t *testing.T, input io.Reader) []Msg { // We'll check that the input reader finishes at the end // without error. var wg sync.WaitGroup var inputErr error ctx, cancel := context.WithCancel(context.Background()) defer func() { cancel() wg.Wait() if inputErr != nil && !errors.Is(inputErr, io.EOF) { t.Fatalf("unexpected input error: %v", inputErr) } }() // The messages we're consuming. msgsC := make(chan Msg) // Start the reader in the background. wg.Add(1) go func() { defer wg.Done() inputErr = readAnsiInputs(ctx, msgsC, input) msgsC <- nil }() var msgs []Msg loop: for { select { case msg := <-msgsC: if msg == nil { // end of input marker for the test. break loop } msgs = append(msgs, msg) case <-time.After(2 * time.Second): t.Errorf("timeout waiting for input event") break loop } } return msgs } // randTest defines the test input and expected output for a sequence // of interleaved control sequences and control characters. type randTest struct { data []byte lengths []int names []string } // seed is the random seed to randomize the input. This helps check // that all the sequences get ultimately exercised. var seed = flag.Int64("seed", 0, "random seed (0 to autoselect)") // genRandomData generates a randomized test, with a random seed unless // the seed flag was set. func genRandomData(logfn func(int64), length int) randTest { // We'll use a random source. However, we give the user the option // to override it to a specific value for reproduceability. s := *seed if s == 0 { s = time.Now().UnixNano() } // Inform the user so they know what to reuse to get the same data. logfn(s) return genRandomDataWithSeed(s, length) } // genRandomDataWithSeed generates a randomized test with a fixed seed. func genRandomDataWithSeed(s int64, length int) randTest { src := rand.NewSource(s) r := rand.New(src) // allseqs contains all the sequences, in sorted order. We sort // to make the test deterministic (when the seed is also fixed). type seqpair struct { seq string name string } var allseqs []seqpair for seq, key := range sequences { allseqs = append(allseqs, seqpair{seq, key.String()}) } sort.Slice(allseqs, func(i, j int) bool { return allseqs[i].seq < allseqs[j].seq }) // res contains the computed test. var res randTest for len(res.data) < length { alt := r.Intn(2) prefix := "" esclen := 0 if alt == 1 { prefix = "alt+" esclen = 1 } kind := r.Intn(3) switch kind { case 0: // A control character. if alt == 1 { res.data = append(res.data, '\x1b') } res.data = append(res.data, 1) res.names = append(res.names, prefix+"ctrl+a") res.lengths = append(res.lengths, 1+esclen) case 1, 2: // A sequence. seqi := r.Intn(len(allseqs)) s := allseqs[seqi] if strings.HasPrefix(s.name, "alt+") { esclen = 0 prefix = "" alt = 0 } if alt == 1 { res.data = append(res.data, '\x1b') } res.data = append(res.data, s.seq...) res.names = append(res.names, prefix+s.name) res.lengths = append(res.lengths, len(s.seq)+esclen) } } return res } // TestDetectRandomSequencesLex checks that the lex-generated sequence // detector works over concatenations of random sequences. func TestDetectRandomSequencesLex(t *testing.T) { runTestDetectSequence(t, detectSequence) } func runTestDetectSequence( t *testing.T, detectSequence func(input []byte) (hasSeq bool, width int, msg Msg), ) { for i := 0; i < 10; i++ { t.Run("", func(t *testing.T) { td := genRandomData(func(s int64) { t.Logf("using random seed: %d", s) }, 1000) t.Logf("%#v", td) // tn is the event number in td. // i is the cursor in the input data. // w is the length of the last sequence detected. for tn, i, w := 0, 0, 0; i < len(td.data); tn, i = tn+1, i+w { hasSequence, width, msg := detectSequence(td.data[i:]) if !hasSequence { t.Fatalf("at %d (ev %d): failed to find sequence", i, tn) } if width != td.lengths[tn] { t.Errorf("at %d (ev %d): expected width %d, got %d", i, tn, td.lengths[tn], width) } w = width s, ok := msg.(fmt.Stringer) if !ok { t.Errorf("at %d (ev %d): expected stringer event, got %T", i, tn, msg) } else { if td.names[tn] != s.String() { t.Errorf("at %d (ev %d): expected event %q, got %q", i, tn, td.names[tn], s.String()) } } } }) } } // TestDetectRandomSequencesMap checks that the map-based sequence // detector works over concatenations of random sequences. func TestDetectRandomSequencesMap(t *testing.T) { runTestDetectSequence(t, detectSequence) } // BenchmarkDetectSequenceMap benchmarks the map-based sequence // detector. func BenchmarkDetectSequenceMap(b *testing.B) { td := genRandomDataWithSeed(123, 10000) for i := 0; i < b.N; i++ { for j, w := 0, 0; j < len(td.data); j += w { _, w, _ = detectSequence(td.data[j:]) } } }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/commands.go
commands.go
package tea import ( "time" ) // Batch performs a bunch of commands concurrently with no ordering guarantees // about the results. Use a Batch to return several commands. // // Example: // // func (m model) Init() Cmd { // return tea.Batch(someCommand, someOtherCommand) // } func Batch(cmds ...Cmd) Cmd { return compactCmds[BatchMsg](cmds) } // BatchMsg is a message used to perform a bunch of commands concurrently with // no ordering guarantees. You can send a BatchMsg with Batch. type BatchMsg []Cmd // Sequence runs the given commands one at a time, in order. Contrast this with // Batch, which runs commands concurrently. func Sequence(cmds ...Cmd) Cmd { return compactCmds[sequenceMsg](cmds) } // sequenceMsg is used internally to run the given commands in order. type sequenceMsg []Cmd // compactCmds ignores any nil commands in cmds, and returns the most direct // command possible. That is, considering the non-nil commands, if there are // none it returns nil, if there is exactly one it returns that command // directly, else it returns the non-nil commands as type T. func compactCmds[T ~[]Cmd](cmds []Cmd) Cmd { var validCmds []Cmd //nolint:prealloc for _, c := range cmds { if c == nil { continue } validCmds = append(validCmds, c) } switch len(validCmds) { case 0: return nil case 1: return validCmds[0] default: return func() Msg { return T(validCmds) } } } // Every is a command that ticks in sync with the system clock. So, if you // wanted to tick with the system clock every second, minute or hour you // could use this. It's also handy for having different things tick in sync. // // Because we're ticking with the system clock the tick will likely not run for // the entire specified duration. For example, if we're ticking for one minute // and the clock is at 12:34:20 then the next tick will happen at 12:35:00, 40 // seconds later. // // To produce the command, pass a duration and a function which returns // a message containing the time at which the tick occurred. // // type TickMsg time.Time // // cmd := Every(time.Second, func(t time.Time) Msg { // return TickMsg(t) // }) // // Beginners' note: Every sends a single message and won't automatically // dispatch messages at an interval. To do that, you'll want to return another // Every command after receiving your tick message. For example: // // type TickMsg time.Time // // // Send a message every second. // func tickEvery() Cmd { // return Every(time.Second, func(t time.Time) Msg { // return TickMsg(t) // }) // } // // func (m model) Init() Cmd { // // Start ticking. // return tickEvery() // } // // func (m model) Update(msg Msg) (Model, Cmd) { // switch msg.(type) { // case TickMsg: // // Return your Every command again to loop. // return m, tickEvery() // } // return m, nil // } // // Every is analogous to Tick in the Elm Architecture. func Every(duration time.Duration, fn func(time.Time) Msg) Cmd { n := time.Now() d := n.Truncate(duration).Add(duration).Sub(n) t := time.NewTimer(d) return func() Msg { ts := <-t.C t.Stop() for len(t.C) > 0 { <-t.C } return fn(ts) } } // Tick produces a command at an interval independent of the system clock at // the given duration. That is, the timer begins precisely when invoked, // and runs for its entire duration. // // To produce the command, pass a duration and a function which returns // a message containing the time at which the tick occurred. // // type TickMsg time.Time // // cmd := Tick(time.Second, func(t time.Time) Msg { // return TickMsg(t) // }) // // Beginners' note: Tick sends a single message and won't automatically // dispatch messages at an interval. To do that, you'll want to return another // Tick command after receiving your tick message. For example: // // type TickMsg time.Time // // func doTick() Cmd { // return Tick(time.Second, func(t time.Time) Msg { // return TickMsg(t) // }) // } // // func (m model) Init() Cmd { // // Start ticking. // return doTick() // } // // func (m model) Update(msg Msg) (Model, Cmd) { // switch msg.(type) { // case TickMsg: // // Return your Tick command again to loop. // return m, doTick() // } // return m, nil // } func Tick(d time.Duration, fn func(time.Time) Msg) Cmd { t := time.NewTimer(d) return func() Msg { ts := <-t.C t.Stop() for len(t.C) > 0 { <-t.C } return fn(ts) } } // Sequentially produces a command that sequentially executes the given // commands. // The Msg returned is the first non-nil message returned by a Cmd. // // func saveStateCmd() Msg { // if err := save(); err != nil { // return errMsg{err} // } // return nil // } // // cmd := Sequentially(saveStateCmd, Quit) // // Deprecated: use Sequence instead. func Sequentially(cmds ...Cmd) Cmd { return func() Msg { for _, cmd := range cmds { if cmd == nil { continue } if msg := cmd(); msg != nil { return msg } } return nil } } // setWindowTitleMsg is an internal message used to set the window title. type setWindowTitleMsg string // SetWindowTitle produces a command that sets the terminal title. // // For example: // // func (m model) Init() Cmd { // // Set title. // return tea.SetWindowTitle("My App") // } func SetWindowTitle(title string) Cmd { return func() Msg { return setWindowTitleMsg(title) } } type windowSizeMsg struct{} // WindowSize is a command that queries the terminal for its current size. It // delivers the results to Update via a [WindowSizeMsg]. Keep in mind that // WindowSizeMsgs will automatically be delivered to Update when the [Program] // starts and when the window dimensions change so in many cases you will not // need to explicitly invoke this command. func WindowSize() Cmd { return func() Msg { return windowSizeMsg{} } }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/logging.go
logging.go
package tea import ( "fmt" "io" "log" "os" "unicode" ) // LogToFile sets up default logging to log to a file. This is helpful as we // can't print to the terminal since our TUI is occupying it. If the file // doesn't exist it will be created. // // Don't forget to close the file when you're done with it. // // f, err := LogToFile("debug.log", "debug") // if err != nil { // fmt.Println("fatal:", err) // os.Exit(1) // } // defer f.Close() func LogToFile(path string, prefix string) (*os.File, error) { return LogToFileWith(path, prefix, log.Default()) } // LogOptionsSetter is an interface implemented by stdlib's log and charm's log // libraries. type LogOptionsSetter interface { SetOutput(io.Writer) SetPrefix(string) } // LogToFileWith does allows to call LogToFile with a custom LogOptionsSetter. func LogToFileWith(path string, prefix string, log LogOptionsSetter) (*os.File, error) { f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o600) //nolint:mnd if err != nil { return nil, fmt.Errorf("error opening file for logging: %w", err) } log.SetOutput(f) // Add a space after the prefix if a prefix is being specified and it // doesn't already have a trailing space. if len(prefix) > 0 { finalChar := prefix[len(prefix)-1] if !unicode.IsSpace(rune(finalChar)) { prefix += " " } } log.SetPrefix(prefix) return f, nil }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/mouse_test.go
mouse_test.go
package tea import ( "fmt" "testing" ) func TestMouseEvent_String(t *testing.T) { tt := []struct { name string event MouseEvent expected string }{ { name: "unknown", event: MouseEvent{ Action: MouseActionPress, Button: MouseButtonNone, Type: MouseUnknown, }, expected: "unknown", }, { name: "left", event: MouseEvent{ Action: MouseActionPress, Button: MouseButtonLeft, Type: MouseLeft, }, expected: "left press", }, { name: "right", event: MouseEvent{ Action: MouseActionPress, Button: MouseButtonRight, Type: MouseRight, }, expected: "right press", }, { name: "middle", event: MouseEvent{ Action: MouseActionPress, Button: MouseButtonMiddle, Type: MouseMiddle, }, expected: "middle press", }, { name: "release", event: MouseEvent{ Action: MouseActionRelease, Button: MouseButtonNone, Type: MouseRelease, }, expected: "release", }, { name: "wheel up", event: MouseEvent{ Action: MouseActionPress, Button: MouseButtonWheelUp, Type: MouseWheelUp, }, expected: "wheel up", }, { name: "wheel down", event: MouseEvent{ Action: MouseActionPress, Button: MouseButtonWheelDown, Type: MouseWheelDown, }, expected: "wheel down", }, { name: "wheel left", event: MouseEvent{ Action: MouseActionPress, Button: MouseButtonWheelLeft, Type: MouseWheelLeft, }, expected: "wheel left", }, { name: "wheel right", event: MouseEvent{ Action: MouseActionPress, Button: MouseButtonWheelRight, Type: MouseWheelRight, }, expected: "wheel right", }, { name: "motion", event: MouseEvent{ Action: MouseActionMotion, Button: MouseButtonNone, Type: MouseMotion, }, expected: "motion", }, { name: "shift+left release", event: MouseEvent{ Type: MouseLeft, Action: MouseActionRelease, Button: MouseButtonLeft, Shift: true, }, expected: "shift+left release", }, { name: "shift+left", event: MouseEvent{ Type: MouseLeft, Action: MouseActionPress, Button: MouseButtonLeft, Shift: true, }, expected: "shift+left press", }, { name: "ctrl+shift+left", event: MouseEvent{ Type: MouseLeft, Action: MouseActionPress, Button: MouseButtonLeft, Shift: true, Ctrl: true, }, expected: "ctrl+shift+left press", }, { name: "alt+left", event: MouseEvent{ Type: MouseLeft, Action: MouseActionPress, Button: MouseButtonLeft, Alt: true, }, expected: "alt+left press", }, { name: "ctrl+left", event: MouseEvent{ Type: MouseLeft, Action: MouseActionPress, Button: MouseButtonLeft, Ctrl: true, }, expected: "ctrl+left press", }, { name: "ctrl+alt+left", event: MouseEvent{ Type: MouseLeft, Action: MouseActionPress, Button: MouseButtonLeft, Alt: true, Ctrl: true, }, expected: "ctrl+alt+left press", }, { name: "ctrl+alt+shift+left", event: MouseEvent{ Type: MouseLeft, Action: MouseActionPress, Button: MouseButtonLeft, Alt: true, Ctrl: true, Shift: true, }, expected: "ctrl+alt+shift+left press", }, { name: "ignore coordinates", event: MouseEvent{ X: 100, Y: 200, Type: MouseLeft, Action: MouseActionPress, Button: MouseButtonLeft, }, expected: "left press", }, { name: "broken type", event: MouseEvent{ Type: MouseEventType(-100), Action: MouseAction(-110), Button: MouseButton(-120), }, expected: "", }, } for i := range tt { tc := tt[i] t.Run(tc.name, func(t *testing.T) { actual := tc.event.String() if tc.expected != actual { t.Fatalf("expected %q but got %q", tc.expected, actual, ) } }) } } func TestParseX10MouseEvent(t *testing.T) { encode := func(b byte, x, y int) []byte { return []byte{ '\x1b', '[', 'M', byte(32) + b, byte(x + 32 + 1), byte(y + 32 + 1), } } tt := []struct { name string buf []byte expected MouseEvent }{ // Position. { name: "zero position", buf: encode(0b0000_0000, 0, 0), expected: MouseEvent{ X: 0, Y: 0, Type: MouseLeft, Action: MouseActionPress, Button: MouseButtonLeft, }, }, { name: "max position", buf: encode(0b0000_0000, 222, 222), // Because 255 (max int8) - 32 - 1. expected: MouseEvent{ X: 222, Y: 222, Type: MouseLeft, Action: MouseActionPress, Button: MouseButtonLeft, }, }, // Simple. { name: "left", buf: encode(0b0000_0000, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Type: MouseLeft, Action: MouseActionPress, Button: MouseButtonLeft, }, }, { name: "left in motion", buf: encode(0b0010_0000, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Type: MouseLeft, Action: MouseActionMotion, Button: MouseButtonLeft, }, }, { name: "middle", buf: encode(0b0000_0001, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Type: MouseMiddle, Action: MouseActionPress, Button: MouseButtonMiddle, }, }, { name: "middle in motion", buf: encode(0b0010_0001, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Type: MouseMiddle, Action: MouseActionMotion, Button: MouseButtonMiddle, }, }, { name: "right", buf: encode(0b0000_0010, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Type: MouseRight, Action: MouseActionPress, Button: MouseButtonRight, }, }, { name: "right in motion", buf: encode(0b0010_0010, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Type: MouseRight, Action: MouseActionMotion, Button: MouseButtonRight, }, }, { name: "motion", buf: encode(0b0010_0011, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Type: MouseMotion, Action: MouseActionMotion, Button: MouseButtonNone, }, }, { name: "wheel up", buf: encode(0b0100_0000, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Type: MouseWheelUp, Action: MouseActionPress, Button: MouseButtonWheelUp, }, }, { name: "wheel down", buf: encode(0b0100_0001, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Type: MouseWheelDown, Action: MouseActionPress, Button: MouseButtonWheelDown, }, }, { name: "wheel left", buf: encode(0b0100_0010, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Type: MouseWheelLeft, Action: MouseActionPress, Button: MouseButtonWheelLeft, }, }, { name: "wheel right", buf: encode(0b0100_0011, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Type: MouseWheelRight, Action: MouseActionPress, Button: MouseButtonWheelRight, }, }, { name: "release", buf: encode(0b0000_0011, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Type: MouseRelease, Action: MouseActionRelease, Button: MouseButtonNone, }, }, { name: "backward", buf: encode(0b1000_0000, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Type: MouseBackward, Action: MouseActionPress, Button: MouseButtonBackward, }, }, { name: "forward", buf: encode(0b1000_0001, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Type: MouseForward, Action: MouseActionPress, Button: MouseButtonForward, }, }, { name: "button 10", buf: encode(0b1000_0010, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Type: MouseUnknown, Action: MouseActionPress, Button: MouseButton10, }, }, { name: "button 11", buf: encode(0b1000_0011, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Type: MouseUnknown, Action: MouseActionPress, Button: MouseButton11, }, }, // Combinations. { name: "alt+right", buf: encode(0b0000_1010, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Alt: true, Type: MouseRight, Action: MouseActionPress, Button: MouseButtonRight, }, }, { name: "ctrl+right", buf: encode(0b0001_0010, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Ctrl: true, Type: MouseRight, Action: MouseActionPress, Button: MouseButtonRight, }, }, { name: "left in motion", buf: encode(0b0010_0000, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Alt: false, Type: MouseLeft, Action: MouseActionMotion, Button: MouseButtonLeft, }, }, { name: "alt+right in motion", buf: encode(0b0010_1010, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Alt: true, Type: MouseRight, Action: MouseActionMotion, Button: MouseButtonRight, }, }, { name: "ctrl+right in motion", buf: encode(0b0011_0010, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Ctrl: true, Type: MouseRight, Action: MouseActionMotion, Button: MouseButtonRight, }, }, { name: "ctrl+alt+right", buf: encode(0b0001_1010, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Alt: true, Ctrl: true, Type: MouseRight, Action: MouseActionPress, Button: MouseButtonRight, }, }, { name: "ctrl+wheel up", buf: encode(0b0101_0000, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Ctrl: true, Type: MouseWheelUp, Action: MouseActionPress, Button: MouseButtonWheelUp, }, }, { name: "alt+wheel down", buf: encode(0b0100_1001, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Alt: true, Type: MouseWheelDown, Action: MouseActionPress, Button: MouseButtonWheelDown, }, }, { name: "ctrl+alt+wheel down", buf: encode(0b0101_1001, 32, 16), expected: MouseEvent{ X: 32, Y: 16, Alt: true, Ctrl: true, Type: MouseWheelDown, Action: MouseActionPress, Button: MouseButtonWheelDown, }, }, // Overflow position. { name: "overflow position", buf: encode(0b0010_0000, 250, 223), // Because 255 (max int8) - 32 - 1. expected: MouseEvent{ X: -6, Y: -33, Type: MouseLeft, Action: MouseActionMotion, Button: MouseButtonLeft, }, }, } for i := range tt { tc := tt[i] t.Run(tc.name, func(t *testing.T) { actual := parseX10MouseEvent(tc.buf) if tc.expected != actual { t.Fatalf("expected %#v but got %#v", tc.expected, actual, ) } }) } } // func TestParseX10MouseEvent_error(t *testing.T) { // tt := []struct { // name string // buf []byte // }{ // { // name: "empty buf", // buf: nil, // }, // { // name: "wrong high bit", // buf: []byte("\x1a[M@A1"), // }, // { // name: "short buf", // buf: []byte("\x1b[M@A"), // }, // { // name: "long buf", // buf: []byte("\x1b[M@A11"), // }, // } // // for i := range tt { // tc := tt[i] // // t.Run(tc.name, func(t *testing.T) { // _, err := parseX10MouseEvent(tc.buf) // // if err == nil { // t.Fatalf("expected error but got nil") // } // }) // } // } func TestParseSGRMouseEvent(t *testing.T) { encode := func(b, x, y int, r bool) []byte { re := 'M' if r { re = 'm' } return []byte(fmt.Sprintf("\x1b[<%d;%d;%d%c", b, x+1, y+1, re)) } tt := []struct { name string buf []byte expected MouseEvent }{ // Position. { name: "zero position", buf: encode(0, 0, 0, false), expected: MouseEvent{ X: 0, Y: 0, Type: MouseLeft, Action: MouseActionPress, Button: MouseButtonLeft, }, }, { name: "225 position", buf: encode(0, 225, 225, false), expected: MouseEvent{ X: 225, Y: 225, Type: MouseLeft, Action: MouseActionPress, Button: MouseButtonLeft, }, }, // Simple. { name: "left", buf: encode(0, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Type: MouseLeft, Action: MouseActionPress, Button: MouseButtonLeft, }, }, { name: "left in motion", buf: encode(32, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Type: MouseLeft, Action: MouseActionMotion, Button: MouseButtonLeft, }, }, { name: "left release", buf: encode(0, 32, 16, true), expected: MouseEvent{ X: 32, Y: 16, Type: MouseRelease, Action: MouseActionRelease, Button: MouseButtonLeft, }, }, { name: "middle", buf: encode(1, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Type: MouseMiddle, Action: MouseActionPress, Button: MouseButtonMiddle, }, }, { name: "middle in motion", buf: encode(33, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Type: MouseMiddle, Action: MouseActionMotion, Button: MouseButtonMiddle, }, }, { name: "middle release", buf: encode(1, 32, 16, true), expected: MouseEvent{ X: 32, Y: 16, Type: MouseRelease, Action: MouseActionRelease, Button: MouseButtonMiddle, }, }, { name: "right", buf: encode(2, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Type: MouseRight, Action: MouseActionPress, Button: MouseButtonRight, }, }, { name: "right release", buf: encode(2, 32, 16, true), expected: MouseEvent{ X: 32, Y: 16, Type: MouseRelease, Action: MouseActionRelease, Button: MouseButtonRight, }, }, { name: "motion", buf: encode(35, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Type: MouseMotion, Action: MouseActionMotion, Button: MouseButtonNone, }, }, { name: "wheel up", buf: encode(64, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Type: MouseWheelUp, Action: MouseActionPress, Button: MouseButtonWheelUp, }, }, { name: "wheel down", buf: encode(65, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Type: MouseWheelDown, Action: MouseActionPress, Button: MouseButtonWheelDown, }, }, { name: "wheel left", buf: encode(66, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Type: MouseWheelLeft, Action: MouseActionPress, Button: MouseButtonWheelLeft, }, }, { name: "wheel right", buf: encode(67, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Type: MouseWheelRight, Action: MouseActionPress, Button: MouseButtonWheelRight, }, }, { name: "backward", buf: encode(128, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Type: MouseBackward, Action: MouseActionPress, Button: MouseButtonBackward, }, }, { name: "backward in motion", buf: encode(160, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Type: MouseBackward, Action: MouseActionMotion, Button: MouseButtonBackward, }, }, { name: "forward", buf: encode(129, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Type: MouseForward, Action: MouseActionPress, Button: MouseButtonForward, }, }, { name: "forward in motion", buf: encode(161, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Type: MouseForward, Action: MouseActionMotion, Button: MouseButtonForward, }, }, // Combinations. { name: "alt+right", buf: encode(10, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Alt: true, Type: MouseRight, Action: MouseActionPress, Button: MouseButtonRight, }, }, { name: "ctrl+right", buf: encode(18, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Ctrl: true, Type: MouseRight, Action: MouseActionPress, Button: MouseButtonRight, }, }, { name: "ctrl+alt+right", buf: encode(26, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Alt: true, Ctrl: true, Type: MouseRight, Action: MouseActionPress, Button: MouseButtonRight, }, }, { name: "alt+wheel press", buf: encode(73, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Alt: true, Type: MouseWheelDown, Action: MouseActionPress, Button: MouseButtonWheelDown, }, }, { name: "ctrl+wheel press", buf: encode(81, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Ctrl: true, Type: MouseWheelDown, Action: MouseActionPress, Button: MouseButtonWheelDown, }, }, { name: "ctrl+alt+wheel press", buf: encode(89, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Alt: true, Ctrl: true, Type: MouseWheelDown, Action: MouseActionPress, Button: MouseButtonWheelDown, }, }, { name: "ctrl+alt+shift+wheel press", buf: encode(93, 32, 16, false), expected: MouseEvent{ X: 32, Y: 16, Shift: true, Alt: true, Ctrl: true, Type: MouseWheelDown, Action: MouseActionPress, Button: MouseButtonWheelDown, }, }, } for i := range tt { tc := tt[i] t.Run(tc.name, func(t *testing.T) { actual := parseSGRMouseEvent(tc.buf) if tc.expected != actual { t.Fatalf("expected %#v but got %#v", tc.expected, actual, ) } }) } }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/renderer.go
renderer.go
package tea // renderer is the interface for Bubble Tea renderers. type renderer interface { // Start the renderer. start() // Stop the renderer, but render the final frame in the buffer, if any. stop() // Stop the renderer without doing any final rendering. kill() // Write a frame to the renderer. The renderer can write this data to // output at its discretion. write(string) // Request a full re-render. Note that this will not trigger a render // immediately. Rather, this method causes the next render to be a full // repaint. Because of this, it's safe to call this method multiple times // in succession. repaint() // Clears the terminal. clearScreen() // Whether or not the alternate screen buffer is enabled. altScreen() bool // Enable the alternate screen buffer. enterAltScreen() // Disable the alternate screen buffer. exitAltScreen() // Show the cursor. showCursor() // Hide the cursor. hideCursor() // enableMouseCellMotion enables mouse click, release, wheel and motion // events if a mouse button is pressed (i.e., drag events). enableMouseCellMotion() // disableMouseCellMotion disables Mouse Cell Motion tracking. disableMouseCellMotion() // enableMouseAllMotion enables mouse click, release, wheel and motion // events, regardless of whether a mouse button is pressed. Many modern // terminals support this, but not all. enableMouseAllMotion() // disableMouseAllMotion disables All Motion mouse tracking. disableMouseAllMotion() // enableMouseSGRMode enables mouse extended mode (SGR). enableMouseSGRMode() // disableMouseSGRMode disables mouse extended mode (SGR). disableMouseSGRMode() // enableBracketedPaste enables bracketed paste, where characters // inside the input are not interpreted when pasted as a whole. enableBracketedPaste() // disableBracketedPaste disables bracketed paste. disableBracketedPaste() // bracketedPasteActive reports whether bracketed paste mode is // currently enabled. bracketedPasteActive() bool // setWindowTitle sets the terminal window title. setWindowTitle(string) // reportFocus returns whether reporting focus events is enabled. reportFocus() bool // enableReportFocus reports focus events to the program. enableReportFocus() // disableReportFocus stops reporting focus events to the program. disableReportFocus() // resetLinesRendered ensures exec output remains on screen on exit resetLinesRendered() } // repaintMsg forces a full repaint. type repaintMsg struct{}
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/screen.go
screen.go
package tea // WindowSizeMsg is used to report the terminal size. It's sent to Update once // initially and then on every terminal resize. Note that Windows does not // have support for reporting when resizes occur as it does not support the // SIGWINCH signal. type WindowSizeMsg struct { Width int Height int } // ClearScreen is a special command that tells the program to clear the screen // before the next update. This can be used to move the cursor to the top left // of the screen and clear visual clutter when the alt screen is not in use. // // Note that it should never be necessary to call ClearScreen() for regular // redraws. func ClearScreen() Msg { return clearScreenMsg{} } // clearScreenMsg is an internal message that signals to clear the screen. // You can send a clearScreenMsg with ClearScreen. type clearScreenMsg struct{} // EnterAltScreen is a special command that tells the Bubble Tea program to // enter the alternate screen buffer. // // Because commands run asynchronously, this command should not be used in your // model's Init function. To initialize your program with the altscreen enabled // use the WithAltScreen ProgramOption instead. func EnterAltScreen() Msg { return enterAltScreenMsg{} } // enterAltScreenMsg in an internal message signals that the program should // enter alternate screen buffer. You can send a enterAltScreenMsg with // EnterAltScreen. type enterAltScreenMsg struct{} // ExitAltScreen is a special command that tells the Bubble Tea program to exit // the alternate screen buffer. This command should be used to exit the // alternate screen buffer while the program is running. // // Note that the alternate screen buffer will be automatically exited when the // program quits. func ExitAltScreen() Msg { return exitAltScreenMsg{} } // exitAltScreenMsg in an internal message signals that the program should exit // alternate screen buffer. You can send a exitAltScreenMsg with ExitAltScreen. type exitAltScreenMsg struct{} // EnableMouseCellMotion is a special command that enables mouse click, // release, and wheel events. Mouse movement events are also captured if // a mouse button is pressed (i.e., drag events). // // Because commands run asynchronously, this command should not be used in your // model's Init function. Use the WithMouseCellMotion ProgramOption instead. func EnableMouseCellMotion() Msg { return enableMouseCellMotionMsg{} } // enableMouseCellMotionMsg is a special command that signals to start // listening for "cell motion" type mouse events (ESC[?1002l). To send an // enableMouseCellMotionMsg, use the EnableMouseCellMotion command. type enableMouseCellMotionMsg struct{} // EnableMouseAllMotion is a special command that enables mouse click, release, // wheel, and motion events, which are delivered regardless of whether a mouse // button is pressed, effectively enabling support for hover interactions. // // Many modern terminals support this, but not all. If in doubt, use // EnableMouseCellMotion instead. // // Because commands run asynchronously, this command should not be used in your // model's Init function. Use the WithMouseAllMotion ProgramOption instead. func EnableMouseAllMotion() Msg { return enableMouseAllMotionMsg{} } // enableMouseAllMotionMsg is a special command that signals to start listening // for "all motion" type mouse events (ESC[?1003l). To send an // enableMouseAllMotionMsg, use the EnableMouseAllMotion command. type enableMouseAllMotionMsg struct{} // DisableMouse is a special command that stops listening for mouse events. func DisableMouse() Msg { return disableMouseMsg{} } // disableMouseMsg is an internal message that signals to stop listening // for mouse events. To send a disableMouseMsg, use the DisableMouse command. type disableMouseMsg struct{} // HideCursor is a special command for manually instructing Bubble Tea to hide // the cursor. In some rare cases, certain operations will cause the terminal // to show the cursor, which is normally hidden for the duration of a Bubble // Tea program's lifetime. You will most likely not need to use this command. func HideCursor() Msg { return hideCursorMsg{} } // hideCursorMsg is an internal command used to hide the cursor. You can send // this message with HideCursor. type hideCursorMsg struct{} // ShowCursor is a special command for manually instructing Bubble Tea to show // the cursor. func ShowCursor() Msg { return showCursorMsg{} } // showCursorMsg is an internal command used to show the cursor. You can send // this message with ShowCursor. type showCursorMsg struct{} // EnableBracketedPaste is a special command that tells the Bubble Tea program // to accept bracketed paste input. // // Note that bracketed paste will be automatically disabled when the // program quits. func EnableBracketedPaste() Msg { return enableBracketedPasteMsg{} } // enableBracketedPasteMsg in an internal message signals that // bracketed paste should be enabled. You can send an // enableBracketedPasteMsg with EnableBracketedPaste. type enableBracketedPasteMsg struct{} // DisableBracketedPaste is a special command that tells the Bubble Tea program // to stop processing bracketed paste input. // // Note that bracketed paste will be automatically disabled when the // program quits. func DisableBracketedPaste() Msg { return disableBracketedPasteMsg{} } // disableBracketedPasteMsg in an internal message signals that // bracketed paste should be disabled. You can send an // disableBracketedPasteMsg with DisableBracketedPaste. type disableBracketedPasteMsg struct{} // enableReportFocusMsg is an internal message that signals to enable focus // reporting. You can send an enableReportFocusMsg with EnableReportFocus. type enableReportFocusMsg struct{} // EnableReportFocus is a special command that tells the Bubble Tea program to // report focus events to the program. func EnableReportFocus() Msg { return enableReportFocusMsg{} } // disableReportFocusMsg is an internal message that signals to disable focus // reporting. You can send an disableReportFocusMsg with DisableReportFocus. type disableReportFocusMsg struct{} // DisableReportFocus is a special command that tells the Bubble Tea program to // stop reporting focus events to the program. func DisableReportFocus() Msg { return disableReportFocusMsg{} } // EnterAltScreen enters the alternate screen buffer, which consumes the entire // terminal window. ExitAltScreen will return the terminal to its former state. // // Deprecated: Use the WithAltScreen ProgramOption instead. func (p *Program) EnterAltScreen() { if p.renderer != nil { p.renderer.enterAltScreen() } else { p.startupOptions |= withAltScreen } } // ExitAltScreen exits the alternate screen buffer. // // Deprecated: The altscreen will exited automatically when the program exits. func (p *Program) ExitAltScreen() { if p.renderer != nil { p.renderer.exitAltScreen() } else { p.startupOptions &^= withAltScreen } } // EnableMouseCellMotion enables mouse click, release, wheel and motion events // if a mouse button is pressed (i.e., drag events). // // Deprecated: Use the WithMouseCellMotion ProgramOption instead. func (p *Program) EnableMouseCellMotion() { if p.renderer != nil { p.renderer.enableMouseCellMotion() } else { p.startupOptions |= withMouseCellMotion } } // DisableMouseCellMotion disables Mouse Cell Motion tracking. This will be // called automatically when exiting a Bubble Tea program. // // Deprecated: The mouse will automatically be disabled when the program exits. func (p *Program) DisableMouseCellMotion() { if p.renderer != nil { p.renderer.disableMouseCellMotion() } else { p.startupOptions &^= withMouseCellMotion } } // EnableMouseAllMotion enables mouse click, release, wheel and motion events, // regardless of whether a mouse button is pressed. Many modern terminals // support this, but not all. // // Deprecated: Use the WithMouseAllMotion ProgramOption instead. func (p *Program) EnableMouseAllMotion() { if p.renderer != nil { p.renderer.enableMouseAllMotion() } else { p.startupOptions |= withMouseAllMotion } } // DisableMouseAllMotion disables All Motion mouse tracking. This will be // called automatically when exiting a Bubble Tea program. // // Deprecated: The mouse will automatically be disabled when the program exits. func (p *Program) DisableMouseAllMotion() { if p.renderer != nil { p.renderer.disableMouseAllMotion() } else { p.startupOptions &^= withMouseAllMotion } } // SetWindowTitle sets the terminal window title. // // Deprecated: Use the SetWindowTitle command instead. func (p *Program) SetWindowTitle(title string) { if p.renderer != nil { p.renderer.setWindowTitle(title) } else { p.startupTitle = title } }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/nil_renderer_test.go
nil_renderer_test.go
package tea import "testing" func TestNilRenderer(t *testing.T) { r := nilRenderer{} r.start() r.stop() r.kill() r.write("a") r.repaint() r.enterAltScreen() if r.altScreen() { t.Errorf("altScreen should always return false") } r.exitAltScreen() r.clearScreen() r.showCursor() r.hideCursor() r.enableMouseCellMotion() r.disableMouseCellMotion() r.enableMouseAllMotion() r.disableMouseAllMotion() }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/inputreader_windows.go
inputreader_windows.go
//go:build windows // +build windows package tea import ( "fmt" "io" "os" "sync" "github.com/charmbracelet/x/term" "github.com/erikgeiser/coninput" "github.com/muesli/cancelreader" "golang.org/x/sys/windows" ) type conInputReader struct { cancelMixin conin windows.Handle originalMode uint32 } var _ cancelreader.CancelReader = &conInputReader{} func newInputReader(r io.Reader, enableMouse bool) (cancelreader.CancelReader, error) { fallback := func(io.Reader) (cancelreader.CancelReader, error) { return cancelreader.NewReader(r) } if f, ok := r.(term.File); !ok || f.Fd() != os.Stdin.Fd() { return fallback(r) } conin, err := coninput.NewStdinHandle() if err != nil { return fallback(r) } modes := []uint32{ windows.ENABLE_WINDOW_INPUT, windows.ENABLE_EXTENDED_FLAGS, } // Since we have options to enable mouse events, [WithMouseCellMotion], // [WithMouseAllMotion], and [EnableMouseCellMotion], // [EnableMouseAllMotion], and [DisableMouse], we need to check if the user // has enabled mouse events and add the appropriate mode accordingly. // Otherwise, mouse events will be enabled all the time. if enableMouse { modes = append(modes, windows.ENABLE_MOUSE_INPUT) } originalMode, err := prepareConsole(conin, modes...) if err != nil { return nil, fmt.Errorf("failed to prepare console input: %w", err) } return &conInputReader{ conin: conin, originalMode: originalMode, }, nil } // Cancel implements cancelreader.CancelReader. func (r *conInputReader) Cancel() bool { r.setCanceled() // Warning: These cancel methods do not reliably work on console input // and should not be counted on. return windows.CancelIoEx(r.conin, nil) == nil || windows.CancelIo(r.conin) == nil } // Close implements cancelreader.CancelReader. func (r *conInputReader) Close() error { if r.originalMode != 0 { err := windows.SetConsoleMode(r.conin, r.originalMode) if err != nil { return fmt.Errorf("reset console mode: %w", err) } } return nil } // Read implements cancelreader.CancelReader. func (r *conInputReader) Read(_ []byte) (n int, err error) { if r.isCanceled() { err = cancelreader.ErrCanceled } return } func prepareConsole(input windows.Handle, modes ...uint32) (originalMode uint32, err error) { err = windows.GetConsoleMode(input, &originalMode) if err != nil { return 0, fmt.Errorf("get console mode: %w", err) } newMode := coninput.AddInputModes(0, modes...) err = windows.SetConsoleMode(input, newMode) if err != nil { return 0, fmt.Errorf("set console mode: %w", err) } return originalMode, nil } // cancelMixin represents a goroutine-safe cancellation status. type cancelMixin struct { unsafeCanceled bool lock sync.Mutex } func (c *cancelMixin) setCanceled() { c.lock.Lock() defer c.lock.Unlock() c.unsafeCanceled = true } func (c *cancelMixin) isCanceled() bool { c.lock.Lock() defer c.lock.Unlock() return c.unsafeCanceled }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/standard_renderer.go
standard_renderer.go
package tea import ( "bytes" "fmt" "io" "strings" "sync" "time" "github.com/charmbracelet/x/ansi" "github.com/muesli/ansi/compressor" ) const ( // defaultFramerate specifies the maximum interval at which we should // update the view. defaultFPS = 60 maxFPS = 120 ) // standardRenderer is a framerate-based terminal renderer, updating the view // at a given framerate to avoid overloading the terminal emulator. // // In cases where very high performance is needed the renderer can be told // to exclude ranges of lines, allowing them to be written to directly. type standardRenderer struct { mtx *sync.Mutex out io.Writer buf bytes.Buffer queuedMessageLines []string framerate time.Duration ticker *time.Ticker done chan struct{} lastRender string lastRenderedLines []string linesRendered int altLinesRendered int useANSICompressor bool once sync.Once // cursor visibility state cursorHidden bool // essentially whether or not we're using the full size of the terminal altScreenActive bool // whether or not we're currently using bracketed paste bpActive bool // reportingFocus whether reporting focus events is enabled reportingFocus bool // renderer dimensions; usually the size of the window width int height int // lines explicitly set not to render ignoreLines map[int]struct{} } // newRenderer creates a new renderer. Normally you'll want to initialize it // with os.Stdout as the first argument. func newRenderer(out io.Writer, useANSICompressor bool, fps int) renderer { if fps < 1 { fps = defaultFPS } else if fps > maxFPS { fps = maxFPS } r := &standardRenderer{ out: out, mtx: &sync.Mutex{}, done: make(chan struct{}), framerate: time.Second / time.Duration(fps), useANSICompressor: useANSICompressor, queuedMessageLines: []string{}, } if r.useANSICompressor { r.out = &compressor.Writer{Forward: out} } return r } // start starts the renderer. func (r *standardRenderer) start() { if r.ticker == nil { r.ticker = time.NewTicker(r.framerate) } else { // If the ticker already exists, it has been stopped and we need to // reset it. r.ticker.Reset(r.framerate) } // Since the renderer can be restarted after a stop, we need to reset // the done channel and its corresponding sync.Once. r.once = sync.Once{} go r.listen() } // stop permanently halts the renderer, rendering the final frame. func (r *standardRenderer) stop() { // Stop the renderer before acquiring the mutex to avoid a deadlock. r.once.Do(func() { r.done <- struct{}{} }) // flush locks the mutex r.flush() r.mtx.Lock() defer r.mtx.Unlock() r.execute(ansi.EraseEntireLine) // Move the cursor back to the beginning of the line r.execute("\r") if r.useANSICompressor { if w, ok := r.out.(io.WriteCloser); ok { _ = w.Close() } } } // execute writes a sequence to the terminal. func (r *standardRenderer) execute(seq string) { _, _ = io.WriteString(r.out, seq) } // kill halts the renderer. The final frame will not be rendered. func (r *standardRenderer) kill() { // Stop the renderer before acquiring the mutex to avoid a deadlock. r.once.Do(func() { r.done <- struct{}{} }) r.mtx.Lock() defer r.mtx.Unlock() r.execute(ansi.EraseEntireLine) // Move the cursor back to the beginning of the line r.execute("\r") } // listen waits for ticks on the ticker, or a signal to stop the renderer. func (r *standardRenderer) listen() { for { select { case <-r.done: r.ticker.Stop() return case <-r.ticker.C: r.flush() } } } // flush renders the buffer. func (r *standardRenderer) flush() { r.mtx.Lock() defer r.mtx.Unlock() if r.buf.Len() == 0 || r.buf.String() == r.lastRender { // Nothing to do. return } // Output buffer. buf := &bytes.Buffer{} // Moving to the beginning of the section, that we rendered. if r.altScreenActive { buf.WriteString(ansi.CursorHomePosition) } else if r.linesRendered > 1 { buf.WriteString(ansi.CursorUp(r.linesRendered - 1)) } newLines := strings.Split(r.buf.String(), "\n") // If we know the output's height, we can use it to determine how many // lines we can render. We drop lines from the top of the render buffer if // necessary, as we can't navigate the cursor into the terminal's scrollback // buffer. if r.height > 0 && len(newLines) > r.height { newLines = newLines[len(newLines)-r.height:] } flushQueuedMessages := len(r.queuedMessageLines) > 0 && !r.altScreenActive if flushQueuedMessages { // Dump the lines we've queued up for printing. for _, line := range r.queuedMessageLines { if ansi.StringWidth(line) < r.width { // We only erase the rest of the line when the line is shorter than // the width of the terminal. When the cursor reaches the end of // the line, any escape sequences that follow will only affect the // last cell of the line. // Removing previously rendered content at the end of line. line = line + ansi.EraseLineRight } _, _ = buf.WriteString(line) _, _ = buf.WriteString("\r\n") } // Clear the queued message lines. r.queuedMessageLines = []string{} } // Paint new lines. for i := 0; i < len(newLines); i++ { canSkip := !flushQueuedMessages && // Queuing messages triggers repaint -> we don't have access to previous frame content. len(r.lastRenderedLines) > i && r.lastRenderedLines[i] == newLines[i] // Previously rendered line is the same. if _, ignore := r.ignoreLines[i]; ignore || canSkip { // Unless this is the last line, move the cursor down. if i < len(newLines)-1 { buf.WriteByte('\n') } continue } if i == 0 && r.lastRender == "" { // On first render, reset the cursor to the start of the line // before writing anything. buf.WriteByte('\r') } line := newLines[i] // Truncate lines wider than the width of the window to avoid // wrapping, which will mess up rendering. If we don't have the // width of the window this will be ignored. // // Note that on Windows we only get the width of the window on // program initialization, so after a resize this won't perform // correctly (signal SIGWINCH is not supported on Windows). if r.width > 0 { line = ansi.Truncate(line, r.width, "") } if ansi.StringWidth(line) < r.width { // We only erase the rest of the line when the line is shorter than // the width of the terminal. When the cursor reaches the end of // the line, any escape sequences that follow will only affect the // last cell of the line. // Removing previously rendered content at the end of line. line = line + ansi.EraseLineRight } _, _ = buf.WriteString(line) if i < len(newLines)-1 { _, _ = buf.WriteString("\r\n") } } // Clearing left over content from last render. if r.lastLinesRendered() > len(newLines) { buf.WriteString(ansi.EraseScreenBelow) } if r.altScreenActive { r.altLinesRendered = len(newLines) } else { r.linesRendered = len(newLines) } // Make sure the cursor is at the start of the last line to keep rendering // behavior consistent. if r.altScreenActive { // This case fixes a bug in macOS terminal. In other terminals the // other case seems to do the job regardless of whether or not we're // using the full terminal window. buf.WriteString(ansi.CursorPosition(0, len(newLines))) } else { buf.WriteByte('\r') } _, _ = r.out.Write(buf.Bytes()) r.lastRender = r.buf.String() // Save previously rendered lines for comparison in the next render. If we // don't do this, we can't skip rendering lines that haven't changed. // See https://github.com/charmbracelet/bubbletea/pull/1233 r.lastRenderedLines = newLines r.buf.Reset() } // lastLinesRendered returns the number of lines rendered lastly. func (r *standardRenderer) lastLinesRendered() int { if r.altScreenActive { return r.altLinesRendered } return r.linesRendered } // write writes to the internal buffer. The buffer will be outputted via the // ticker which calls flush(). func (r *standardRenderer) write(s string) { r.mtx.Lock() defer r.mtx.Unlock() r.buf.Reset() // If an empty string was passed we should clear existing output and // rendering nothing. Rather than introduce additional state to manage // this, we render a single space as a simple (albeit less correct) // solution. if s == "" { s = " " } _, _ = r.buf.WriteString(s) } func (r *standardRenderer) repaint() { r.lastRender = "" r.lastRenderedLines = nil } func (r *standardRenderer) clearScreen() { r.mtx.Lock() defer r.mtx.Unlock() r.execute(ansi.EraseEntireScreen) r.execute(ansi.CursorHomePosition) r.repaint() } func (r *standardRenderer) altScreen() bool { r.mtx.Lock() defer r.mtx.Unlock() return r.altScreenActive } func (r *standardRenderer) enterAltScreen() { r.mtx.Lock() defer r.mtx.Unlock() if r.altScreenActive { return } r.altScreenActive = true r.execute(ansi.SetAltScreenSaveCursorMode) // Ensure that the terminal is cleared, even when it doesn't support // alt screen (or alt screen support is disabled, like GNU screen by // default). // // Note: we can't use r.clearScreen() here because the mutex is already // locked. r.execute(ansi.EraseEntireScreen) r.execute(ansi.CursorHomePosition) // cmd.exe and other terminals keep separate cursor states for the AltScreen // and the main buffer. We have to explicitly reset the cursor visibility // whenever we enter AltScreen. if r.cursorHidden { r.execute(ansi.HideCursor) } else { r.execute(ansi.ShowCursor) } // Entering the alt screen resets the lines rendered count. r.altLinesRendered = 0 r.repaint() } func (r *standardRenderer) exitAltScreen() { r.mtx.Lock() defer r.mtx.Unlock() if !r.altScreenActive { return } r.altScreenActive = false r.execute(ansi.ResetAltScreenSaveCursorMode) // cmd.exe and other terminals keep separate cursor states for the AltScreen // and the main buffer. We have to explicitly reset the cursor visibility // whenever we exit AltScreen. if r.cursorHidden { r.execute(ansi.HideCursor) } else { r.execute(ansi.ShowCursor) } r.repaint() } func (r *standardRenderer) showCursor() { r.mtx.Lock() defer r.mtx.Unlock() r.cursorHidden = false r.execute(ansi.ShowCursor) } func (r *standardRenderer) hideCursor() { r.mtx.Lock() defer r.mtx.Unlock() r.cursorHidden = true r.execute(ansi.HideCursor) } func (r *standardRenderer) enableMouseCellMotion() { r.mtx.Lock() defer r.mtx.Unlock() r.execute(ansi.SetButtonEventMouseMode) } func (r *standardRenderer) disableMouseCellMotion() { r.mtx.Lock() defer r.mtx.Unlock() r.execute(ansi.ResetButtonEventMouseMode) } func (r *standardRenderer) enableMouseAllMotion() { r.mtx.Lock() defer r.mtx.Unlock() r.execute(ansi.SetAnyEventMouseMode) } func (r *standardRenderer) disableMouseAllMotion() { r.mtx.Lock() defer r.mtx.Unlock() r.execute(ansi.ResetAnyEventMouseMode) } func (r *standardRenderer) enableMouseSGRMode() { r.mtx.Lock() defer r.mtx.Unlock() r.execute(ansi.SetSgrExtMouseMode) } func (r *standardRenderer) disableMouseSGRMode() { r.mtx.Lock() defer r.mtx.Unlock() r.execute(ansi.ResetSgrExtMouseMode) } func (r *standardRenderer) enableBracketedPaste() { r.mtx.Lock() defer r.mtx.Unlock() r.execute(ansi.SetBracketedPasteMode) r.bpActive = true } func (r *standardRenderer) disableBracketedPaste() { r.mtx.Lock() defer r.mtx.Unlock() r.execute(ansi.ResetBracketedPasteMode) r.bpActive = false } func (r *standardRenderer) bracketedPasteActive() bool { r.mtx.Lock() defer r.mtx.Unlock() return r.bpActive } func (r *standardRenderer) enableReportFocus() { r.mtx.Lock() defer r.mtx.Unlock() r.execute(ansi.SetFocusEventMode) r.reportingFocus = true } func (r *standardRenderer) disableReportFocus() { r.mtx.Lock() defer r.mtx.Unlock() r.execute(ansi.ResetFocusEventMode) r.reportingFocus = false } func (r *standardRenderer) reportFocus() bool { r.mtx.Lock() defer r.mtx.Unlock() return r.reportingFocus } // setWindowTitle sets the terminal window title. func (r *standardRenderer) setWindowTitle(title string) { r.execute(ansi.SetWindowTitle(title)) } // setIgnoredLines specifies lines not to be touched by the standard Bubble Tea // renderer. func (r *standardRenderer) setIgnoredLines(from int, to int) { // Lock if we're going to be clearing some lines since we don't want // anything jacking our cursor. if r.lastLinesRendered() > 0 { r.mtx.Lock() defer r.mtx.Unlock() } if r.ignoreLines == nil { r.ignoreLines = make(map[int]struct{}) } for i := from; i < to; i++ { r.ignoreLines[i] = struct{}{} } // Erase ignored lines lastLinesRendered := r.lastLinesRendered() if lastLinesRendered > 0 { buf := &bytes.Buffer{} for i := lastLinesRendered - 1; i >= 0; i-- { if _, exists := r.ignoreLines[i]; exists { buf.WriteString(ansi.EraseEntireLine) } buf.WriteString(ansi.CUU1) } buf.WriteString(ansi.CursorPosition(0, lastLinesRendered)) // put cursor back _, _ = r.out.Write(buf.Bytes()) } } // clearIgnoredLines returns control of any ignored lines to the standard // Bubble Tea renderer. That is, any lines previously set to be ignored can be // rendered to again. func (r *standardRenderer) clearIgnoredLines() { r.ignoreLines = nil } func (r *standardRenderer) resetLinesRendered() { r.linesRendered = 0 } // insertTop effectively scrolls up. It inserts lines at the top of a given // area designated to be a scrollable region, pushing everything else down. // This is roughly how ncurses does it. // // To call this function use command ScrollUp(). // // For this to work renderer.ignoreLines must be set to ignore the scrollable // region since we are bypassing the normal Bubble Tea renderer here. // // Because this method relies on the terminal dimensions, it's only valid for // full-window applications (generally those that use the alternate screen // buffer). // // This method bypasses the normal rendering buffer and is philosophically // different than the normal way we approach rendering in Bubble Tea. It's for // use in high-performance rendering, such as a pager that could potentially // be rendering very complicated ansi. In cases where the content is simpler // standard Bubble Tea rendering should suffice. // // Deprecated: This option is deprecated and will be removed in a future // version of this package. func (r *standardRenderer) insertTop(lines []string, topBoundary, bottomBoundary int) { r.mtx.Lock() defer r.mtx.Unlock() buf := &bytes.Buffer{} buf.WriteString(ansi.SetTopBottomMargins(topBoundary, bottomBoundary)) buf.WriteString(ansi.CursorPosition(0, topBoundary)) buf.WriteString(ansi.InsertLine(len(lines))) _, _ = buf.WriteString(strings.Join(lines, "\r\n")) buf.WriteString(ansi.SetTopBottomMargins(0, r.height)) // Move cursor back to where the main rendering routine expects it to be buf.WriteString(ansi.CursorPosition(0, r.lastLinesRendered())) _, _ = r.out.Write(buf.Bytes()) } // insertBottom effectively scrolls down. It inserts lines at the bottom of // a given area designated to be a scrollable region, pushing everything else // up. This is roughly how ncurses does it. // // To call this function use the command ScrollDown(). // // See note in insertTop() for caveats, how this function only makes sense for // full-window applications, and how it differs from the normal way we do // rendering in Bubble Tea. // // Deprecated: This option is deprecated and will be removed in a future // version of this package. func (r *standardRenderer) insertBottom(lines []string, topBoundary, bottomBoundary int) { r.mtx.Lock() defer r.mtx.Unlock() buf := &bytes.Buffer{} buf.WriteString(ansi.SetTopBottomMargins(topBoundary, bottomBoundary)) buf.WriteString(ansi.CursorPosition(0, bottomBoundary)) _, _ = buf.WriteString("\r\n" + strings.Join(lines, "\r\n")) buf.WriteString(ansi.SetTopBottomMargins(0, r.height)) // Move cursor back to where the main rendering routine expects it to be buf.WriteString(ansi.CursorPosition(0, r.lastLinesRendered())) _, _ = r.out.Write(buf.Bytes()) } // handleMessages handles internal messages for the renderer. func (r *standardRenderer) handleMessages(msg Msg) { switch msg := msg.(type) { case repaintMsg: // Force a repaint by clearing the render cache as we slide into a // render. r.mtx.Lock() r.repaint() r.mtx.Unlock() case WindowSizeMsg: r.mtx.Lock() r.width = msg.Width r.height = msg.Height r.repaint() r.mtx.Unlock() case clearScrollAreaMsg: r.clearIgnoredLines() // Force a repaint on the area where the scrollable stuff was in this // update cycle r.mtx.Lock() r.repaint() r.mtx.Unlock() case syncScrollAreaMsg: // Re-render scrolling area r.clearIgnoredLines() r.setIgnoredLines(msg.topBoundary, msg.bottomBoundary) r.insertTop(msg.lines, msg.topBoundary, msg.bottomBoundary) // Force non-scrolling stuff to repaint in this update cycle r.mtx.Lock() r.repaint() r.mtx.Unlock() case scrollUpMsg: r.insertTop(msg.lines, msg.topBoundary, msg.bottomBoundary) case scrollDownMsg: r.insertBottom(msg.lines, msg.topBoundary, msg.bottomBoundary) case printLineMessage: if !r.altScreenActive { lines := strings.Split(msg.messageBody, "\n") r.mtx.Lock() r.queuedMessageLines = append(r.queuedMessageLines, lines...) r.repaint() r.mtx.Unlock() } } } // HIGH-PERFORMANCE RENDERING STUFF type syncScrollAreaMsg struct { lines []string topBoundary int bottomBoundary int } // SyncScrollArea performs a paint of the entire region designated to be the // scrollable area. This is required to initialize the scrollable region and // should also be called on resize (WindowSizeMsg). // // For high-performance, scroll-based rendering only. // // Deprecated: This option will be removed in a future version of this package. func SyncScrollArea(lines []string, topBoundary int, bottomBoundary int) Cmd { return func() Msg { return syncScrollAreaMsg{ lines: lines, topBoundary: topBoundary, bottomBoundary: bottomBoundary, } } } type clearScrollAreaMsg struct{} // ClearScrollArea deallocates the scrollable region and returns the control of // those lines to the main rendering routine. // // For high-performance, scroll-based rendering only. // // Deprecated: This option will be removed in a future version of this package. func ClearScrollArea() Msg { return clearScrollAreaMsg{} } type scrollUpMsg struct { lines []string topBoundary int bottomBoundary int } // ScrollUp adds lines to the top of the scrollable region, pushing existing // lines below down. Lines that are pushed out the scrollable region disappear // from view. // // For high-performance, scroll-based rendering only. // // Deprecated: This option will be removed in a future version of this package. func ScrollUp(newLines []string, topBoundary, bottomBoundary int) Cmd { return func() Msg { return scrollUpMsg{ lines: newLines, topBoundary: topBoundary, bottomBoundary: bottomBoundary, } } } type scrollDownMsg struct { lines []string topBoundary int bottomBoundary int } // ScrollDown adds lines to the bottom of the scrollable region, pushing // existing lines above up. Lines that are pushed out of the scrollable region // disappear from view. // // For high-performance, scroll-based rendering only. // // Deprecated: This option will be removed in a future version of this package. func ScrollDown(newLines []string, topBoundary, bottomBoundary int) Cmd { return func() Msg { return scrollDownMsg{ lines: newLines, topBoundary: topBoundary, bottomBoundary: bottomBoundary, } } } type printLineMessage struct { messageBody string } // Println prints above the Program. This output is unmanaged by the program and // will persist across renders by the Program. // // Unlike fmt.Println (but similar to log.Println) the message will be print on // its own line. // // If the altscreen is active no output will be printed. func Println(args ...interface{}) Cmd { return func() Msg { return printLineMessage{ messageBody: fmt.Sprint(args...), } } } // Printf prints above the Program. It takes a format template followed by // values similar to fmt.Printf. This output is unmanaged by the program and // will persist across renders by the Program. // // Unlike fmt.Printf (but similar to log.Printf) the message will be print on // its own line. // // If the altscreen is active no output will be printed. func Printf(template string, args ...interface{}) Cmd { return func() Msg { return printLineMessage{ messageBody: fmt.Sprintf(template, args...), } } }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/screen_test.go
screen_test.go
package tea import ( "bytes" "testing" ) func TestClearMsg(t *testing.T) { tests := []struct { name string cmds sequenceMsg expected string }{ { name: "clear_screen", cmds: []Cmd{ClearScreen}, expected: "\x1b[?25l\x1b[?2004h\x1b[2J\x1b[H\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l", }, { name: "altscreen", cmds: []Cmd{EnterAltScreen, ExitAltScreen}, expected: "\x1b[?25l\x1b[?2004h\x1b[?1049h\x1b[2J\x1b[H\x1b[?25l\x1b[?1049l\x1b[?25l\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l", }, { name: "altscreen_autoexit", cmds: []Cmd{EnterAltScreen}, expected: "\x1b[?25l\x1b[?2004h\x1b[?1049h\x1b[2J\x1b[H\x1b[?25l\x1b[H\rsuccess\x1b[K\r\n\x1b[K\x1b[2;H\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1049l\x1b[?25h", }, { name: "mouse_cellmotion", cmds: []Cmd{EnableMouseCellMotion}, expected: "\x1b[?25l\x1b[?2004h\x1b[?1002h\x1b[?1006h\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l", }, { name: "mouse_allmotion", cmds: []Cmd{EnableMouseAllMotion}, expected: "\x1b[?25l\x1b[?2004h\x1b[?1003h\x1b[?1006h\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l", }, { name: "mouse_disable", cmds: []Cmd{EnableMouseAllMotion, DisableMouse}, expected: "\x1b[?25l\x1b[?2004h\x1b[?1003h\x1b[?1006h\x1b[?1002l\x1b[?1003l\x1b[?1006l\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l", }, { name: "cursor_hide", cmds: []Cmd{HideCursor}, expected: "\x1b[?25l\x1b[?2004h\x1b[?25l\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l", }, { name: "cursor_hideshow", cmds: []Cmd{HideCursor, ShowCursor}, expected: "\x1b[?25l\x1b[?2004h\x1b[?25l\x1b[?25h\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l", }, { name: "bp_stop_start", cmds: []Cmd{DisableBracketedPaste, EnableBracketedPaste}, expected: "\x1b[?25l\x1b[?2004h\x1b[?2004l\x1b[?2004h\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { var buf bytes.Buffer var in bytes.Buffer m := &testModel{} p := NewProgram(m, WithInput(&in), WithOutput(&buf)) test.cmds = append([]Cmd{func() Msg { return WindowSizeMsg{80, 24} }}, test.cmds...) test.cmds = append(test.cmds, Quit) go p.Send(test.cmds) if _, err := p.Run(); err != nil { t.Fatal(err) } if buf.String() != test.expected { t.Errorf("expected embedded sequence:\n%q\ngot:\n%q", test.expected, buf.String()) } }) } }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/tea.go
tea.go
// Package tea provides a framework for building rich terminal user interfaces // based on the paradigms of The Elm Architecture. It's well-suited for simple // and complex terminal applications, either inline, full-window, or a mix of // both. It's been battle-tested in several large projects and is // production-ready. // // A tutorial is available at https://github.com/charmbracelet/bubbletea/tree/master/tutorials // // Example programs can be found at https://github.com/charmbracelet/bubbletea/tree/master/examples package tea import ( "context" "errors" "fmt" "io" "os" "os/signal" "runtime" "runtime/debug" "sync" "sync/atomic" "syscall" "github.com/charmbracelet/x/term" "github.com/muesli/cancelreader" ) // ErrProgramPanic is returned by [Program.Run] when the program recovers from a panic. var ErrProgramPanic = errors.New("program experienced a panic") // ErrProgramKilled is returned by [Program.Run] when the program gets killed. var ErrProgramKilled = errors.New("program was killed") // ErrInterrupted is returned by [Program.Run] when the program get a SIGINT // signal, or when it receives a [InterruptMsg]. var ErrInterrupted = errors.New("program was interrupted") // Msg contain data from the result of a IO operation. Msgs trigger the update // function and, henceforth, the UI. type Msg interface{} // Model contains the program's state as well as its core functions. type Model interface { // Init is the first function that will be called. It returns an optional // initial command. To not perform an initial command return nil. Init() Cmd // Update is called when a message is received. Use it to inspect messages // and, in response, update the model and/or send a command. Update(Msg) (Model, Cmd) // View renders the program's UI, which is just a string. The view is // rendered after every Update. View() string } // Cmd is an IO operation that returns a message when it's complete. If it's // nil it's considered a no-op. Use it for things like HTTP requests, timers, // saving and loading from disk, and so on. // // Note that there's almost never a reason to use a command to send a message // to another part of your program. That can almost always be done in the // update function. type Cmd func() Msg type inputType int const ( defaultInput inputType = iota ttyInput customInput ) // String implements the stringer interface for [inputType]. It is intended to // be used in testing. func (i inputType) String() string { return [...]string{ "default input", "tty input", "custom input", }[i] } // Options to customize the program during its initialization. These are // generally set with ProgramOptions. // // The options here are treated as bits. type startupOptions int16 func (s startupOptions) has(option startupOptions) bool { return s&option != 0 } const ( withAltScreen startupOptions = 1 << iota withMouseCellMotion withMouseAllMotion withANSICompressor withoutSignalHandler // Catching panics is incredibly useful for restoring the terminal to a // usable state after a panic occurs. When this is set, Bubble Tea will // recover from panics, print the stack trace, and disable raw mode. This // feature is on by default. withoutCatchPanics withoutBracketedPaste withReportFocus ) // channelHandlers manages the series of channels returned by various processes. // It allows us to wait for those processes to terminate before exiting the // program. type channelHandlers []chan struct{} // Adds a channel to the list of handlers. We wait for all handlers to terminate // gracefully on shutdown. func (h *channelHandlers) add(ch chan struct{}) { *h = append(*h, ch) } // shutdown waits for all handlers to terminate. func (h channelHandlers) shutdown() { var wg sync.WaitGroup for _, ch := range h { wg.Add(1) go func(ch chan struct{}) { <-ch wg.Done() }(ch) } wg.Wait() } // Program is a terminal user interface. type Program struct { initialModel Model // handlers is a list of channels that need to be waited on before the // program can exit. handlers channelHandlers // Configuration options that will set as the program is initializing, // treated as bits. These options can be set via various ProgramOptions. startupOptions startupOptions // startupTitle is the title that will be set on the terminal when the // program starts. startupTitle string inputType inputType // externalCtx is a context that was passed in via WithContext, otherwise defaulting // to ctx.Background() (in case it was not), the internal context is derived from it. externalCtx context.Context // ctx is the programs's internal context for signalling internal teardown. // It is built and derived from the externalCtx in NewProgram(). ctx context.Context cancel context.CancelFunc msgs chan Msg errs chan error finished chan struct{} // where to send output, this will usually be os.Stdout. output io.Writer // ttyOutput is null if output is not a TTY. ttyOutput term.File previousOutputState *term.State renderer renderer // the environment variables for the program, defaults to os.Environ(). environ []string // where to read inputs from, this will usually be os.Stdin. input io.Reader // ttyInput is null if input is not a TTY. ttyInput term.File previousTtyInputState *term.State cancelReader cancelreader.CancelReader readLoopDone chan struct{} // was the altscreen active before releasing the terminal? altScreenWasActive bool ignoreSignals uint32 bpWasActive bool // was the bracketed paste mode active before releasing the terminal? reportFocus bool // was focus reporting active before releasing the terminal? filter func(Model, Msg) Msg // fps is the frames per second we should set on the renderer, if // applicable, fps int // mouseMode is true if the program should enable mouse mode on Windows. mouseMode bool } // Quit is a special command that tells the Bubble Tea program to exit. func Quit() Msg { return QuitMsg{} } // QuitMsg signals that the program should quit. You can send a [QuitMsg] with // [Quit]. type QuitMsg struct{} // Suspend is a special command that tells the Bubble Tea program to suspend. func Suspend() Msg { return SuspendMsg{} } // SuspendMsg signals the program should suspend. // This usually happens when ctrl+z is pressed on common programs, but since // bubbletea puts the terminal in raw mode, we need to handle it in a // per-program basis. // // You can send this message with [Suspend()]. type SuspendMsg struct{} // ResumeMsg can be listen to do something once a program is resumed back // from a suspend state. type ResumeMsg struct{} // InterruptMsg signals the program should suspend. // This usually happens when ctrl+c is pressed on common programs, but since // bubbletea puts the terminal in raw mode, we need to handle it in a // per-program basis. // // You can send this message with [Interrupt()]. type InterruptMsg struct{} // Interrupt is a special command that tells the Bubble Tea program to // interrupt. func Interrupt() Msg { return InterruptMsg{} } // NewProgram creates a new Program. func NewProgram(model Model, opts ...ProgramOption) *Program { p := &Program{ initialModel: model, msgs: make(chan Msg), } // Apply all options to the program. for _, opt := range opts { opt(p) } // A context can be provided with a ProgramOption, but if none was provided // we'll use the default background context. if p.externalCtx == nil { p.externalCtx = context.Background() } // Initialize context and teardown channel. p.ctx, p.cancel = context.WithCancel(p.externalCtx) // if no output was set, set it to stdout if p.output == nil { p.output = os.Stdout } // if no environment was set, set it to os.Environ() if p.environ == nil { p.environ = os.Environ() } return p } func (p *Program) handleSignals() chan struct{} { ch := make(chan struct{}) // Listen for SIGINT and SIGTERM. // // In most cases ^C will not send an interrupt because the terminal will be // in raw mode and ^C will be captured as a keystroke and sent along to // Program.Update as a KeyMsg. When input is not a TTY, however, ^C will be // caught here. // // SIGTERM is sent by unix utilities (like kill) to terminate a process. go func() { sig := make(chan os.Signal, 1) signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) defer func() { signal.Stop(sig) close(ch) }() for { select { case <-p.ctx.Done(): return case s := <-sig: if atomic.LoadUint32(&p.ignoreSignals) == 0 { switch s { case syscall.SIGINT: p.msgs <- InterruptMsg{} default: p.msgs <- QuitMsg{} } return } } } }() return ch } // handleResize handles terminal resize events. func (p *Program) handleResize() chan struct{} { ch := make(chan struct{}) if p.ttyOutput != nil { // Get the initial terminal size and send it to the program. go p.checkResize() // Listen for window resizes. go p.listenForResize(ch) } else { close(ch) } return ch } // handleCommands runs commands in a goroutine and sends the result to the // program's message channel. func (p *Program) handleCommands(cmds chan Cmd) chan struct{} { ch := make(chan struct{}) go func() { defer close(ch) for { select { case <-p.ctx.Done(): return case cmd := <-cmds: if cmd == nil { continue } // Don't wait on these goroutines, otherwise the shutdown // latency would get too large as a Cmd can run for some time // (e.g. tick commands that sleep for half a second). It's not // possible to cancel them so we'll have to leak the goroutine // until Cmd returns. go func() { // Recover from panics. if !p.startupOptions.has(withoutCatchPanics) { defer func() { if r := recover(); r != nil { p.recoverFromGoPanic(r) } }() } msg := cmd() // this can be long. p.Send(msg) }() } } }() return ch } func (p *Program) disableMouse() { p.renderer.disableMouseCellMotion() p.renderer.disableMouseAllMotion() p.renderer.disableMouseSGRMode() } // eventLoop is the central message loop. It receives and handles the default // Bubble Tea messages, update the model and triggers redraws. func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) { for { select { case <-p.ctx.Done(): return model, nil case err := <-p.errs: return model, err case msg := <-p.msgs: // Filter messages. if p.filter != nil { msg = p.filter(model, msg) } if msg == nil { continue } // Handle special internal messages. switch msg := msg.(type) { case QuitMsg: return model, nil case InterruptMsg: return model, ErrInterrupted case SuspendMsg: if suspendSupported { p.suspend() } case clearScreenMsg: p.renderer.clearScreen() case enterAltScreenMsg: p.renderer.enterAltScreen() case exitAltScreenMsg: p.renderer.exitAltScreen() case enableMouseCellMotionMsg, enableMouseAllMotionMsg: switch msg.(type) { case enableMouseCellMotionMsg: p.renderer.enableMouseCellMotion() case enableMouseAllMotionMsg: p.renderer.enableMouseAllMotion() } // mouse mode (1006) is a no-op if the terminal doesn't support it. p.renderer.enableMouseSGRMode() // XXX: This is used to enable mouse mode on Windows. We need // to reinitialize the cancel reader to get the mouse events to // work. if runtime.GOOS == "windows" && !p.mouseMode { p.mouseMode = true p.initCancelReader(true) //nolint:errcheck,gosec } case disableMouseMsg: p.disableMouse() // XXX: On Windows, mouse mode is enabled on the input reader // level. We need to instruct the input reader to stop reading // mouse events. if runtime.GOOS == "windows" && p.mouseMode { p.mouseMode = false p.initCancelReader(true) //nolint:errcheck,gosec } case showCursorMsg: p.renderer.showCursor() case hideCursorMsg: p.renderer.hideCursor() case enableBracketedPasteMsg: p.renderer.enableBracketedPaste() case disableBracketedPasteMsg: p.renderer.disableBracketedPaste() case enableReportFocusMsg: p.renderer.enableReportFocus() case disableReportFocusMsg: p.renderer.disableReportFocus() case execMsg: // NB: this blocks. p.exec(msg.cmd, msg.fn) case BatchMsg: go p.execBatchMsg(msg) continue case sequenceMsg: go p.execSequenceMsg(msg) continue case setWindowTitleMsg: p.SetWindowTitle(string(msg)) case windowSizeMsg: go p.checkResize() } // Process internal messages for the renderer. if r, ok := p.renderer.(*standardRenderer); ok { r.handleMessages(msg) } var cmd Cmd model, cmd = model.Update(msg) // run update select { case <-p.ctx.Done(): return model, nil case cmds <- cmd: // process command (if any) } p.renderer.write(model.View()) // send view to renderer } } } func (p *Program) execSequenceMsg(msg sequenceMsg) { if !p.startupOptions.has(withoutCatchPanics) { defer func() { if r := recover(); r != nil { p.recoverFromGoPanic(r) } }() } // Execute commands one at a time, in order. for _, cmd := range msg { if cmd == nil { continue } msg := cmd() switch msg := msg.(type) { case BatchMsg: p.execBatchMsg(msg) case sequenceMsg: p.execSequenceMsg(msg) default: p.Send(msg) } } } func (p *Program) execBatchMsg(msg BatchMsg) { if !p.startupOptions.has(withoutCatchPanics) { defer func() { if r := recover(); r != nil { p.recoverFromGoPanic(r) } }() } // Execute commands one at a time. var wg sync.WaitGroup for _, cmd := range msg { if cmd == nil { continue } wg.Add(1) go func() { defer wg.Done() if !p.startupOptions.has(withoutCatchPanics) { defer func() { if r := recover(); r != nil { p.recoverFromGoPanic(r) } }() } msg := cmd() switch msg := msg.(type) { case BatchMsg: p.execBatchMsg(msg) case sequenceMsg: p.execSequenceMsg(msg) default: p.Send(msg) } }() } wg.Wait() // wait for all commands from batch msg to finish } // Run initializes the program and runs its event loops, blocking until it gets // terminated by either [Program.Quit], [Program.Kill], or its signal handler. // Returns the final model. func (p *Program) Run() (returnModel Model, returnErr error) { p.handlers = channelHandlers{} cmds := make(chan Cmd) p.errs = make(chan error, 1) p.finished = make(chan struct{}) defer func() { close(p.finished) }() defer p.cancel() switch p.inputType { case defaultInput: p.input = os.Stdin // The user has not set a custom input, so we need to check whether or // not standard input is a terminal. If it's not, we open a new TTY for // input. This will allow things to "just work" in cases where data was // piped in or redirected to the application. // // To disable input entirely pass nil to the [WithInput] program option. f, isFile := p.input.(term.File) if !isFile { break } if term.IsTerminal(f.Fd()) { break } f, err := openInputTTY() if err != nil { return p.initialModel, err } defer f.Close() //nolint:errcheck p.input = f case ttyInput: // Open a new TTY, by request f, err := openInputTTY() if err != nil { return p.initialModel, err } defer f.Close() //nolint:errcheck p.input = f case customInput: // (There is nothing extra to do.) } // Handle signals. if !p.startupOptions.has(withoutSignalHandler) { p.handlers.add(p.handleSignals()) } // Recover from panics. if !p.startupOptions.has(withoutCatchPanics) { defer func() { if r := recover(); r != nil { returnErr = fmt.Errorf("%w: %w", ErrProgramKilled, ErrProgramPanic) p.recoverFromPanic(r) } }() } // If no renderer is set use the standard one. if p.renderer == nil { p.renderer = newRenderer(p.output, p.startupOptions.has(withANSICompressor), p.fps) } // Check if output is a TTY before entering raw mode, hiding the cursor and // so on. if err := p.initTerminal(); err != nil { return p.initialModel, err } // Honor program startup options. if p.startupTitle != "" { p.renderer.setWindowTitle(p.startupTitle) } if p.startupOptions&withAltScreen != 0 { p.renderer.enterAltScreen() } if p.startupOptions&withoutBracketedPaste == 0 { p.renderer.enableBracketedPaste() } if p.startupOptions&withMouseCellMotion != 0 { p.renderer.enableMouseCellMotion() p.renderer.enableMouseSGRMode() } else if p.startupOptions&withMouseAllMotion != 0 { p.renderer.enableMouseAllMotion() p.renderer.enableMouseSGRMode() } // XXX: Should we enable mouse mode on Windows? // This needs to happen before initializing the cancel and input reader. p.mouseMode = p.startupOptions&withMouseCellMotion != 0 || p.startupOptions&withMouseAllMotion != 0 if p.startupOptions&withReportFocus != 0 { p.renderer.enableReportFocus() } // Start the renderer. p.renderer.start() // Initialize the program. model := p.initialModel if initCmd := model.Init(); initCmd != nil { ch := make(chan struct{}) p.handlers.add(ch) go func() { defer close(ch) select { case cmds <- initCmd: case <-p.ctx.Done(): } }() } // Render the initial view. p.renderer.write(model.View()) // Subscribe to user input. if p.input != nil { if err := p.initCancelReader(false); err != nil { return model, err } } // Handle resize events. p.handlers.add(p.handleResize()) // Process commands. p.handlers.add(p.handleCommands(cmds)) // Run event loop, handle updates and draw. model, err := p.eventLoop(model, cmds) if err == nil && len(p.errs) > 0 { err = <-p.errs // Drain a leftover error in case eventLoop crashed } killed := p.externalCtx.Err() != nil || p.ctx.Err() != nil || err != nil if killed { if err == nil && p.externalCtx.Err() != nil { // Return also as context error the cancellation of an external context. // This is the context the user knows about and should be able to act on. err = fmt.Errorf("%w: %w", ErrProgramKilled, p.externalCtx.Err()) } else if err == nil && p.ctx.Err() != nil { // Return only that the program was killed (not the internal mechanism). // The user does not know or need to care about the internal program context. err = ErrProgramKilled } else { // Return that the program was killed and also the error that caused it. err = fmt.Errorf("%w: %w", ErrProgramKilled, err) } } else { // Graceful shutdown of the program (not killed): // Ensure we rendered the final state of the model. p.renderer.write(model.View()) } // Restore terminal state. p.shutdown(killed) return model, err } // StartReturningModel initializes the program and runs its event loops, // blocking until it gets terminated by either [Program.Quit], [Program.Kill], // or its signal handler. Returns the final model. // // Deprecated: please use [Program.Run] instead. func (p *Program) StartReturningModel() (Model, error) { return p.Run() } // Start initializes the program and runs its event loops, blocking until it // gets terminated by either [Program.Quit], [Program.Kill], or its signal // handler. // // Deprecated: please use [Program.Run] instead. func (p *Program) Start() error { _, err := p.Run() return err } // Send sends a message to the main update function, effectively allowing // messages to be injected from outside the program for interoperability // purposes. // // If the program hasn't started yet this will be a blocking operation. // If the program has already been terminated this will be a no-op, so it's safe // to send messages after the program has exited. func (p *Program) Send(msg Msg) { select { case <-p.ctx.Done(): case p.msgs <- msg: } } // Quit is a convenience function for quitting Bubble Tea programs. Use it // when you need to shut down a Bubble Tea program from the outside. // // If you wish to quit from within a Bubble Tea program use the Quit command. // // If the program is not running this will be a no-op, so it's safe to call // if the program is unstarted or has already exited. func (p *Program) Quit() { p.Send(Quit()) } // Kill signals the program to stop immediately and restore the former terminal state. // The final render that you would normally see when quitting will be skipped. // [program.Run] returns a [ErrProgramKilled] error. func (p *Program) Kill() { p.cancel() } // Wait waits/blocks until the underlying Program finished shutting down. func (p *Program) Wait() { <-p.finished } // shutdown performs operations to free up resources and restore the terminal // to its original state. It is called once at the end of the program's lifetime. // // This method should not be called to signal the program to be killed/shutdown. // Doing so can lead to race conditions with the eventual call at the program's end. // As alternatives, the [Quit] or [Kill] convenience methods should be used instead. func (p *Program) shutdown(kill bool) { p.cancel() // Wait for all handlers to finish. p.handlers.shutdown() // Check if the cancel reader has been setup before waiting and closing. if p.cancelReader != nil { // Wait for input loop to finish. if p.cancelReader.Cancel() { if !kill { p.waitForReadLoop() } } _ = p.cancelReader.Close() } if p.renderer != nil { if kill { p.renderer.kill() } else { p.renderer.stop() } } _ = p.restoreTerminalState() } // recoverFromPanic recovers from a panic, prints the stack trace, and restores // the terminal to a usable state. func (p *Program) recoverFromPanic(r interface{}) { select { case p.errs <- ErrProgramPanic: default: } p.shutdown(true) // Ok to call here, p.Run() cannot do it anymore. fmt.Printf("Caught panic:\n\n%s\n\nRestoring terminal...\n\n", r) debug.PrintStack() } // recoverFromGoPanic recovers from a goroutine panic, prints a stack trace and // signals for the program to be killed and terminal restored to a usable state. func (p *Program) recoverFromGoPanic(r interface{}) { select { case p.errs <- ErrProgramPanic: default: } p.cancel() fmt.Printf("Caught goroutine panic:\n\n%s\n\nRestoring terminal...\n\n", r) debug.PrintStack() } // ReleaseTerminal restores the original terminal state and cancels the input // reader. You can return control to the Program with RestoreTerminal. func (p *Program) ReleaseTerminal() error { atomic.StoreUint32(&p.ignoreSignals, 1) if p.cancelReader != nil { p.cancelReader.Cancel() } p.waitForReadLoop() if p.renderer != nil { p.renderer.stop() p.altScreenWasActive = p.renderer.altScreen() p.bpWasActive = p.renderer.bracketedPasteActive() p.reportFocus = p.renderer.reportFocus() } return p.restoreTerminalState() } // RestoreTerminal reinitializes the Program's input reader, restores the // terminal to the former state when the program was running, and repaints. // Use it to reinitialize a Program after running ReleaseTerminal. func (p *Program) RestoreTerminal() error { atomic.StoreUint32(&p.ignoreSignals, 0) if err := p.initTerminal(); err != nil { return err } if err := p.initCancelReader(false); err != nil { return err } if p.altScreenWasActive { p.renderer.enterAltScreen() } else { // entering alt screen already causes a repaint. go p.Send(repaintMsg{}) } if p.renderer != nil { p.renderer.start() } if p.bpWasActive { p.renderer.enableBracketedPaste() } if p.reportFocus { p.renderer.enableReportFocus() } // If the output is a terminal, it may have been resized while another // process was at the foreground, in which case we may not have received // SIGWINCH. Detect any size change now and propagate the new size as // needed. go p.checkResize() return nil } // Println prints above the Program. This output is unmanaged by the program // and will persist across renders by the Program. // // If the altscreen is active no output will be printed. func (p *Program) Println(args ...interface{}) { p.msgs <- printLineMessage{ messageBody: fmt.Sprint(args...), } } // Printf prints above the Program. It takes a format template followed by // values similar to fmt.Printf. This output is unmanaged by the program and // will persist across renders by the Program. // // Unlike fmt.Printf (but similar to log.Printf) the message will be print on // its own line. // // If the altscreen is active no output will be printed. func (p *Program) Printf(template string, args ...interface{}) { p.msgs <- printLineMessage{ messageBody: fmt.Sprintf(template, args...), } }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/tty.go
tty.go
package tea import ( "errors" "fmt" "io" "time" "github.com/charmbracelet/x/term" "github.com/muesli/cancelreader" ) func (p *Program) suspend() { if err := p.ReleaseTerminal(); err != nil { // If we can't release input, abort. return } suspendProcess() _ = p.RestoreTerminal() go p.Send(ResumeMsg{}) } func (p *Program) initTerminal() error { if _, ok := p.renderer.(*nilRenderer); ok { // No need to initialize the terminal if we're not rendering return nil } if err := p.initInput(); err != nil { return err } p.renderer.hideCursor() return nil } // restoreTerminalState restores the terminal to the state prior to running the // Bubble Tea program. func (p *Program) restoreTerminalState() error { if p.renderer != nil { p.renderer.disableBracketedPaste() p.renderer.showCursor() p.disableMouse() if p.renderer.reportFocus() { p.renderer.disableReportFocus() } if p.renderer.altScreen() { p.renderer.exitAltScreen() // give the terminal a moment to catch up time.Sleep(time.Millisecond * 10) //nolint:mnd } } return p.restoreInput() } // restoreInput restores the tty input to its original state. func (p *Program) restoreInput() error { if p.ttyInput != nil && p.previousTtyInputState != nil { if err := term.Restore(p.ttyInput.Fd(), p.previousTtyInputState); err != nil { return fmt.Errorf("error restoring console: %w", err) } } if p.ttyOutput != nil && p.previousOutputState != nil { if err := term.Restore(p.ttyOutput.Fd(), p.previousOutputState); err != nil { return fmt.Errorf("error restoring console: %w", err) } } return nil } // initCancelReader (re)commences reading inputs. func (p *Program) initCancelReader(cancel bool) error { if cancel && p.cancelReader != nil { p.cancelReader.Cancel() p.waitForReadLoop() } var err error p.cancelReader, err = newInputReader(p.input, p.mouseMode) if err != nil { return fmt.Errorf("error creating cancelreader: %w", err) } p.readLoopDone = make(chan struct{}) go p.readLoop() return nil } func (p *Program) readLoop() { defer close(p.readLoopDone) err := readInputs(p.ctx, p.msgs, p.cancelReader) if !errors.Is(err, io.EOF) && !errors.Is(err, cancelreader.ErrCanceled) { select { case <-p.ctx.Done(): case p.errs <- err: } } } // waitForReadLoop waits for the cancelReader to finish its read loop. func (p *Program) waitForReadLoop() { select { case <-p.readLoopDone: case <-time.After(500 * time.Millisecond): //nolint:mnd // The read loop hangs, which means the input // cancelReader's cancel function has returned true even // though it was not able to cancel the read. } } // checkResize detects the current size of the output and informs the program // via a WindowSizeMsg. func (p *Program) checkResize() { if p.ttyOutput == nil { // can't query window size return } w, h, err := term.GetSize(p.ttyOutput.Fd()) if err != nil { select { case <-p.ctx.Done(): case p.errs <- err: } return } p.Send(WindowSizeMsg{ Width: w, Height: h, }) }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/exec_test.go
exec_test.go
package tea import ( "bytes" "os/exec" "runtime" "testing" ) type execFinishedMsg struct{ err error } type testExecModel struct { cmd string err error } func (m testExecModel) Init() Cmd { c := exec.Command(m.cmd) //nolint:gosec return ExecProcess(c, func(err error) Msg { return execFinishedMsg{err} }) } func (m *testExecModel) Update(msg Msg) (Model, Cmd) { switch msg := msg.(type) { case execFinishedMsg: if msg.err != nil { m.err = msg.err } return m, Quit } return m, nil } func (m *testExecModel) View() string { return "\n" } type spyRenderer struct { renderer calledReset bool } func (r *spyRenderer) resetLinesRendered() { r.calledReset = true r.renderer.resetLinesRendered() } func TestTeaExec(t *testing.T) { type test struct { name string cmd string expectErr bool } tests := []test{ { name: "invalid command", cmd: "invalid", expectErr: true, }, } if runtime.GOOS != "windows" { tests = append(tests, []test{ { name: "true", cmd: "true", expectErr: false, }, { name: "false", cmd: "false", expectErr: true, }, }...) } for _, test := range tests { t.Run(test.name, func(t *testing.T) { var buf bytes.Buffer var in bytes.Buffer m := &testExecModel{cmd: test.cmd} p := NewProgram(m, WithInput(&in), WithOutput(&buf)) if _, err := p.Run(); err != nil { t.Error(err) } p.renderer = &spyRenderer{renderer: p.renderer} if m.err != nil && !test.expectErr { t.Errorf("expected no error, got %v", m.err) if !p.renderer.(*spyRenderer).calledReset { t.Error("expected renderer to be reset") } } if m.err == nil && test.expectErr { t.Error("expected error, got nil") } }) } }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/signals_windows.go
signals_windows.go
//go:build windows // +build windows package tea // listenForResize is not available on windows because windows does not // implement syscall.SIGWINCH. func (p *Program) listenForResize(done chan struct{}) { close(done) }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/key_sequences.go
key_sequences.go
package tea import ( "bytes" "sort" "unicode/utf8" ) // extSequences is used by the map-based algorithm below. It contains // the sequences plus their alternatives with an escape character // prefixed, plus the control chars, plus the space. // It does not contain the NUL character, which is handled specially // by detectOneMsg. var extSequences = func() map[string]Key { s := map[string]Key{} for seq, key := range sequences { s[seq] = key if !key.Alt { key.Alt = true s["\x1b"+seq] = key } } for i := keyNUL + 1; i <= keyDEL; i++ { if i == keyESC { continue } s[string([]byte{byte(i)})] = Key{Type: i} s[string([]byte{'\x1b', byte(i)})] = Key{Type: i, Alt: true} if i == keyUS { i = keyDEL - 1 } } s[" "] = Key{Type: KeySpace, Runes: spaceRunes} s["\x1b "] = Key{Type: KeySpace, Alt: true, Runes: spaceRunes} s["\x1b\x1b"] = Key{Type: KeyEscape, Alt: true} return s }() // seqLengths is the sizes of valid sequences, starting with the // largest size. var seqLengths = func() []int { sizes := map[int]struct{}{} for seq := range extSequences { sizes[len(seq)] = struct{}{} } lsizes := make([]int, 0, len(sizes)) for sz := range sizes { lsizes = append(lsizes, sz) } sort.Slice(lsizes, func(i, j int) bool { return lsizes[i] > lsizes[j] }) return lsizes }() // detectSequence uses a longest prefix match over the input // sequence and a hash map. func detectSequence(input []byte) (hasSeq bool, width int, msg Msg) { seqs := extSequences for _, sz := range seqLengths { if sz > len(input) { continue } prefix := input[:sz] key, ok := seqs[string(prefix)] if ok { return true, sz, KeyMsg(key) } } // Is this an unknown CSI sequence? if loc := unknownCSIRe.FindIndex(input); loc != nil { return true, loc[1], unknownCSISequenceMsg(input[:loc[1]]) } return false, 0, nil } // detectBracketedPaste detects an input pasted while bracketed // paste mode was enabled. // // Note: this function is a no-op if bracketed paste was not enabled // on the terminal, since in that case we'd never see this // particular escape sequence. func detectBracketedPaste(input []byte) (hasBp bool, width int, msg Msg) { // Detect the start sequence. const bpStart = "\x1b[200~" if len(input) < len(bpStart) || string(input[:len(bpStart)]) != bpStart { return false, 0, nil } // Skip over the start sequence. input = input[len(bpStart):] // If we saw the start sequence, then we must have an end sequence // as well. Find it. const bpEnd = "\x1b[201~" idx := bytes.Index(input, []byte(bpEnd)) inputLen := len(bpStart) + idx + len(bpEnd) if idx == -1 { // We have encountered the end of the input buffer without seeing // the marker for the end of the bracketed paste. // Tell the outer loop we have done a short read and we want more. return true, 0, nil } // The paste is everything in-between. paste := input[:idx] // All there is in-between is runes, not to be interpreted further. k := Key{Type: KeyRunes, Paste: true} for len(paste) > 0 { r, w := utf8.DecodeRune(paste) if r != utf8.RuneError { k.Runes = append(k.Runes, r) } paste = paste[w:] } return true, inputLen, KeyMsg(k) } // detectReportFocus detects a focus report sequence. func detectReportFocus(input []byte) (hasRF bool, width int, msg Msg) { switch { case bytes.Equal(input, []byte("\x1b[I")): return true, 3, FocusMsg{} //nolint:mnd case bytes.Equal(input, []byte("\x1b[O")): return true, 3, BlurMsg{} //nolint:mnd } return false, 0, nil }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/commands_test.go
commands_test.go
package tea import ( "fmt" "testing" "time" ) func TestEvery(t *testing.T) { expected := "every ms" msg := Every(time.Millisecond, func(t time.Time) Msg { return expected })() if expected != msg { t.Fatalf("expected a msg %v but got %v", expected, msg) } } func TestTick(t *testing.T) { expected := "tick" msg := Tick(time.Millisecond, func(t time.Time) Msg { return expected })() if expected != msg { t.Fatalf("expected a msg %v but got %v", expected, msg) } } func TestSequentially(t *testing.T) { expectedErrMsg := fmt.Errorf("some err") expectedStrMsg := "some msg" nilReturnCmd := func() Msg { return nil } tests := []struct { name string cmds []Cmd expected Msg }{ { name: "all nil", cmds: []Cmd{nilReturnCmd, nilReturnCmd}, expected: nil, }, { name: "null cmds", cmds: []Cmd{nil, nil}, expected: nil, }, { name: "one error", cmds: []Cmd{ nilReturnCmd, func() Msg { return expectedErrMsg }, nilReturnCmd, }, expected: expectedErrMsg, }, { name: "some msg", cmds: []Cmd{ nilReturnCmd, func() Msg { return expectedStrMsg }, nilReturnCmd, }, expected: expectedStrMsg, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { if msg := Sequentially(test.cmds...)(); msg != test.expected { t.Fatalf("expected a msg %v but got %v", test.expected, msg) } }) } } func TestBatch(t *testing.T) { testMultipleCommands[BatchMsg](t, Batch) } func TestSequence(t *testing.T) { testMultipleCommands[sequenceMsg](t, Sequence) } func testMultipleCommands[T ~[]Cmd](t *testing.T, createFn func(cmd ...Cmd) Cmd) { t.Run("nil cmd", func(t *testing.T) { if b := createFn(nil); b != nil { t.Fatalf("expected nil, got %+v", b) } }) t.Run("empty cmd", func(t *testing.T) { if b := createFn(); b != nil { t.Fatalf("expected nil, got %+v", b) } }) t.Run("single cmd", func(t *testing.T) { b := createFn(Quit)() if _, ok := b.(QuitMsg); !ok { t.Fatalf("expected a QuitMsg, got %T", b) } }) t.Run("mixed nil cmds", func(t *testing.T) { b := createFn(nil, Quit, nil, Quit, nil, nil)() if l := len(b.(T)); l != 2 { t.Fatalf("expected a []Cmd with len 2, got %d", l) } }) }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/signals_unix.go
signals_unix.go
//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || aix || zos // +build darwin dragonfly freebsd linux netbsd openbsd solaris aix zos package tea import ( "os" "os/signal" "syscall" ) // listenForResize sends messages (or errors) when the terminal resizes. // Argument output should be the file descriptor for the terminal; usually // os.Stdout. func (p *Program) listenForResize(done chan struct{}) { sig := make(chan os.Signal, 1) signal.Notify(sig, syscall.SIGWINCH) defer func() { signal.Stop(sig) close(done) }() for { select { case <-p.ctx.Done(): return case <-sig: } p.checkResize() } }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false
charmbracelet/bubbletea
https://github.com/charmbracelet/bubbletea/blob/f9233d51192293dadda7184a4de347738606c328/tea_init.go
tea_init.go
package tea import ( "github.com/charmbracelet/lipgloss" ) func init() { // XXX: This is a workaround to make assure that Lip Gloss and Termenv // query the terminal before any Bubble Tea Program runs and acquires the // terminal. Without this, Programs that use Lip Gloss/Termenv might hang // while waiting for a a [termenv.OSCTimeout] while querying the terminal // for its background/foreground colors. // // This happens because Bubble Tea acquires the terminal before termenv // reads any responses. // // Note that this will only affect programs running on the default IO i.e. // [os.Stdout] and [os.Stdin]. // // This workaround will be removed in v2. _ = lipgloss.HasDarkBackground() }
go
MIT
f9233d51192293dadda7184a4de347738606c328
2026-01-07T08:35:58.083951Z
false