Go Workshop - Dia 4
https://golang-workshop.io
Rodolfo Finochietti
Rodolfo Finochietti
"Gin is a high-performance micro-framework that delivers a very minimalistic framework that carries with it only the most essential features, libraries, and functionalities needed to build web applications and microservices."
3$ go get -u github.com/gin-gonic/gin $ go get -u github.com/gin-gonic/contrib/static
El paquete https://golang.org/pkg/net/http/ contiene una implementacion de un cliente http que permite emular las acciones que realiza un web browser.
6resp, _ := http.Get("https://httpbin.org/get") defer resp.Body.Close() data, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(data))
payload := "Hello world!" resp, _ := http.Post("https://httpbin.org/post", "text/plain", strings.NewReader(payload)) defer resp.Body.Close() data, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(data))
Functional Programming by Wikipedia:
Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data
En otras palabras la programacion funcional promueve codigo sin cambios en los valores de las variables para evitar efectos no esperados.
Es lo opuesto de la programacion imperativa, que enfatiza los cambios de estado.
9Esto quiere decir que:
No hay razon para lo que Einstein definio como locura: "hacer la misma cosa una y otra vez esperando diferentes resultados"
Golang es un lenguaje de programacion multi-lenguaje, no es un lenguaje funcional, pero tiene caracteristicas que nos permiten desarrollar codigo que aplique los principios de la programacion funcional.
12Strings
Mal
name := "Juan" name := name + " Carlos"
Bien
const firstname = "Juan Carlos" const lasname = "Batman" const name = firstname + " " + lastname
Arrays
Mal
years := [4]int{2001, 2002} years[2] = 2003 years[3] = 2004 years // [2001, 2002, 2003, 2004]
Bien
years := [2]int{2001, 2001} allYears := append(years, 2003, [2]int{2004, 2005}
Maps
Mal
ages := map[string]int{"John": 30} ages["Mary"] = 28 ages // {"John": 30, "Mary": 28}
Bien
ages1 := map[string]int{"John": 30} ages2 := map[string]int{"Mary": 28} func mergeMaps(mapA, mapB map[string]int) map[string]int { allAges := make(map[K]V, len(ages1) + len(ages2)) for k, v := range mapA { allAges[k] = v } for k, v := range mapB { allAges[k] = v } return allAges } allAges := mergeMaps(ages1, ages2)
Las funciones son first-class objects en Golang, si se quiere pasar una funcion a otra funcion, se debe tratar como cualquier otro objeto.
func caller(f func(string) string) { result := f("Juan") fmt.Println(result) } f := func(s name) string { return "Hola " + name } caller(f)
Tener higher order functions habilita el currying, que es la posibilidad de tomar una funcion que recibe n parametros y convertirla en la composicion de n funciones que reciben 1 parametro:
func plus(x, y int) int { return x + y } func partialPlus(x int) func(int) int { return func(y int) int { return plus(x, y) } } func main() { plus_one := partialPlus(1) fmt.Println(plus_one(5)) //prints 6 }
Crear un proyecto
$ gcloud projects create PROJECT_ID
Configurar el proyecto por defecto en nuestro entorno
$ gcloud config set project PROJECT_ID
Crear una nueva aplicacion en GAE
$ gcloud app create
Agregar un archivo app.yaml
runtime: go115 env_variables: GOLANGORG_CHECK_COUNTRY: true nobuild_files: views/
Subir la aplicacion a GAE
$ gcloud app deploy
Abrir la aplicacion
$ gcloud app browse
* Building a Go App on App Engine
20$ curl -O https://storage.googleapis.com/golang/go1.16.windows-386.zip $ unzip go1.16.windows-386.zip Comprobar la ultima version en https://golang.org/dl No preocuparse si aparece el error Bad Request
http.ListenAndServe(":"+os.Getenv("HTTP_PLATFORM_PORT"), nil)
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="httpplatformhandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" /> </handlers> <httpPlatform processPath="d:\home\site\wwwroot\go\bin\go.exe" arguments="run d:\home\site\wwwroot\server.go" startupTimeLimit="60"> <environmentVariables> <environmentVariable name="GOROOT" value="d:\home\site\wwwroot\go" /> </environmentVariables> </httpPlatform> </system.webServer> </configuration>
Modificar la API Rest del challenge 3.3 para usar Gin.
24