9. Debugging is twice as hard as writing the
code in the first place. Therefore, if you
write the code as cleverly as possible,
you are, by definition, not smart enough
to debug it.
BRIAN KERNIGHAN
14. TYPES & METHODS
02. CODE
type Abser interface {
Abs() float64
}
Interfaces specify behaviors.
An interface type defines a set
of methods:
Types implement interfaces implicitly. There is no “implements” declaration.
func PrintAbs(a Abser) {
fmt.Printf("Absolute value:
%.2fn", a.Abs())
}
PrintAbs(MyFloat(-10))
PrintAbs(Point{3, 4})
A type that implements those
methods implements the
interface:
16. Hello GDGGranada
04. SAMPLE & RUN
package main
import “fmt”
func main() {
fmt.Printf(“hello, gdgn”)
}
Make dir src/hello in your
workspace, and create file
named hello.go
cd $HOME/go/src/hello
go run hello.go
17. Hello GDGGranada
04. BUILD
env GOOS=target-OS GOARCH=target-architecture go build
env GOOS=windows GOARCH=386 go build
go build
How many OS and Arch?
30. Ready Backend
Backend API
type Etsiitiano struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Hobbies []string `json:"hobbies,omitempty"`
Address Address `json:"address,omitempty"`
}
type Address struct {
City string `json:"city,omitempty"`
State string `json:"state,omitempty"`
}
31. Ready Backend
Backend API
func GetStudents(w http.ResponseWriter, r *http.Request) {
GetOutput(students, w, r.Header.Get("Type"))
}
32. Ready Backend
Backend API
func GetStudent(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for _, item := range students {
if item.ID == params["id"] {
GetOutput(item, w, r.Header.Get("Type"))
return
}
}
GetOutput(&Etsiitiano{}, w, r.Header.Get("Type"))
}
33. Ready Backend
Backend API
func CreateStudent(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
var person Etsiitiano
error := json.NewDecoder(r.Body).Decode(&person)
if error != nil{
log.Fatal(error)
}
person.ID = params["id"]
students = append(students, person)
GetOutput(students, w, r.Header.Get("Type"))
}
34. Ready Backend
Backend API
func DeleteStudent(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for index, item := range students {
if item.ID == params["id"] {
students = append(students[:index], students[index+1:]...)
break
}
GetOutput(students, w, r.Header.Get("Type"))
}
}
35. Ready Backend
Backend API
curl -X GET localhost:8000/students -H "type: json"
curl -X POST localhost:8000/student/3 -H "type: json" -d '{"name":"Alberto"}'
curl -X DELETE localhost:8000/student/3 -H "type: json"
36. Ready Backend
Backend API
curl -X GET localhost:8000/students -H "type: json"
curl -X POST localhost:8000/student/3 -H "type: json" -d '{"name":"Alberto"}'
curl -X DELETE localhost:8000/student/3 -H "type: json"