Outils pour utilisateurs

Outils du site


issue121:c_c

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Prochaine révision
Révision précédente
issue121:c_c [2017/05/29 16:52] – créée auntieeissue121:c_c [2017/06/11 14:07] (Version actuelle) auntiee
Ligne 1: Ligne 1:
-I recently started working on a project using Google’s Go programming language. As I had previously only completed the tour and a few minor tasks, this was my first experience using it for a larger project. Over the course of the project, I am essentially creating a web app (linked to a PostgreSQL database). I won’t go into the details of the actual project, but I will be sharing what I’ve learned so far.+**I recently started working on a project using Google’s Go programming language. As I had previously only completed the tour and a few minor tasks, this was my first experience using it for a larger project. Over the course of the project, I am essentially creating a web app (linked to a PostgreSQL database). I won’t go into the details of the actual project, but I will be sharing what I’ve learned so far.**
  
-The Setup+J'ai commencé récemment à travailler sur un projet utilisant le langage de programmation Go de Google. Comme je ne l'avait regardé que brièvement et fait quelques tâches mineures auparavant, c'était ma première expérience de son utilisation sur un grand projet. Durant le projet, j'ai principalement créé une appli Web (liée à une base de données PostgreSQL). Je ne rentrerai pas dans les détails du véritable projet, mais je vais partager ce que j'ai déjà appris. 
 + 
 +**The Setup
  
 You can install Go using apt: You can install Go using apt:
Ligne 7: Ligne 9:
  sudo apt-get install golang-go  sudo apt-get install golang-go
  
-If you want a more recent version of Go, there are more instructions on their GitHub page: https://github.com/golang/go/wiki/Ubuntu +If you want a more recent version of Go, there are more instructions on their GitHub page: https://github.com/golang/go/wiki/Ubuntu **
  
-Example Code+Le paramétrage 
 + 
 +Vous pouvez installer Go en utilisant apt : 
 + 
 + sudo apt-get install golang-go 
 + 
 +Si vous voulez une version plus récente de Go, il y a des instructions supplémentaires sur leur page GitHub : https://github.com/golang/go/wiki/Ubuntu 
 + 
 +**Example Code
  
 I’ve thrown together a small set of sample code into a Gist, which can be found here: https://gist.github.com/lswest/feed0fb8685b0d9bed03e864a78f7f1a I’ve thrown together a small set of sample code into a Gist, which can be found here: https://gist.github.com/lswest/feed0fb8685b0d9bed03e864a78f7f1a
  
-If you decide to download the files, be sure to place the two html files in a subdirectory called “tmpl”, or update the path in the app.go file.+If you decide to download the files, be sure to place the two html files in a subdirectory called “tmpl”, or update the path in the app.go file.**
  
-The Basics+Exemple de code 
 + 
 +J'ai regroupé un petit jeu d'exemples de code dans un Gist, que vous pouvez trouver ici : https://gist.github.com/lswest/feed0fb8685b0d9bed03e864a78f7f1a 
 + 
 +Si vous décidez de télécharger les fichiers, veillez à placer les deux fichiers html dans un sous-répertoire appelé « tmpl » ou mettez à jour le chemin dans le fichier app.go. 
 + 
 +**The Basics
  
 There is a tour over at https://tour.golang.org/welcome/1 which is a very good spot to start. Naturally, you can also follow other tutorials or books. There is a tour over at https://tour.golang.org/welcome/1 which is a very good spot to start. Naturally, you can also follow other tutorials or books.
  
-Once you’ve written your code, you can either compile it using go build or run it locally using go run. While Go can be used for other projects besides web-based apps, I won’t be going into detail for those uses.+Once you’ve written your code, you can either compile it using go build or run it locally using go run. While Go can be used for other projects besides web-based apps, I won’t be going into detail for those uses.**
  
-Templating+Les bases 
 + 
 +Il y a une présentation sur https://tour.golang.org/welcome/1 qui est un très bon point de départ. Naturellement, vous pouvez suivre aussi d'autres tutoriels ou livres. 
 + 
 +Une fois que vous avez écrit votre code, vous pouvez, soit le compiler en utilisant « go build », soit le lancer localement en utilisant « go run ». Même si Go peut être utilisé pour des projets autres que les applis basées sur le Web, je ne vais pas rentrer dans le détail pour ces utilisations. 
 + 
 +**Templating
  
 The above example code is essentially a ‘hello world’ application, but covering a few aspects that I had trouble implementing correctly right off the bat. A few important notes: The above example code is essentially a ‘hello world’ application, but covering a few aspects that I had trouble implementing correctly right off the bat. A few important notes:
Ligne 27: Ligne 49:
 • On the same line, the ParseGlob line is necessary for working with partial templates, as, without it, the {{define “header”}} line would not be parsed, leading to errors. If you’re not using a tmpl directory, ParseGlob(“*”) should work. • On the same line, the ParseGlob line is necessary for working with partial templates, as, without it, the {{define “header”}} line would not be parsed, leading to errors. If you’re not using a tmpl directory, ParseGlob(“*”) should work.
  
-Generally, this templating works pretty much like Jinja2, for anyone who has used that. Dynamic elements (such as those loaded from structs) are in curly braces, and all fields begin with a “.”, indicating that you’re expecting to find the variable in the current object. Filters are attached to variables via a pipe. Stringing multiple filters together should work (though I haven’t tested it).+Generally, this templating works pretty much like Jinja2, for anyone who has used that. Dynamic elements (such as those loaded from structs) are in curly braces, and all fields begin with a “.”, indicating that you’re expecting to find the variable in the current object. Filters are attached to variables via a pipe. Stringing multiple filters together should work (though I haven’t tested it).**
  
-URLs+Les modèles 
 + 
 +le code exemple ci-dessus est principalement une application « hello world », mais recouvrant quelques aspects que j'ai eu du mal à implémenter correctement d'entrée de jeu. Quelques notes importantes : 
 +• À la ligne 23 (https://gist.github.com/lswest/feed0fb8685b0d9bed03e864a78f7f1a#file-app-go-L23), la section Funcs(funcMap) incorpore des filtres personnalisés à utiliser dans le modèle (dans ce cas, cela active le filtre ToLower). 
 +• Sur la même ligne, la ligne ParseGlob est nécessaire pour travailler avec des modèles partiels, car, sans cela, la ligne {{define “header”}} ne sera pas analysée, conduisant à des erreurs. Si vous n'utilisez pas un répertoire tmpl, ParseGlob(“*”) devrait fonctionner. 
 + 
 +De manière générale, cette préparation de modèles fonctionne de manière proche de Jinja2, pour tous ceux qui l'ont utilisé. Les éléments dynamiques (tels que ceux chargés à partir de « structs ») sont entre accolades, et tous les champs commencent par un « . », indiquant que vous vous attendez à trouver la variable dans l'objet courant. Les filtres sont attachés aux variables via un pipe. Mettre plusieurs filtres à la queue leu-leu devrait fonctionner (bien que je ne l'aie pas testé). 
 + 
 +**URLs
  
 If you execute ‘go run’ in the project directory, navigating to http://localhost:8081/ will yield a generic looking “Hello World” file. If, however, you head to http://localhost:8081/Lucas, the page will instead greet the name given in the URL. If you execute ‘go run’ in the project directory, navigating to http://localhost:8081/ will yield a generic looking “Hello World” file. If, however, you head to http://localhost:8081/Lucas, the page will instead greet the name given in the URL.
Ligne 37: Ligne 67:
 The code itself is relatively straightforward - on line 15, I set up the generic page, and then I check if the length of the URL Path (everything after the domain) is longer than the length of “/” (so, 1). If the length is longer, that means there is a parameter given (in this case, the name), and the ‘hello’ variable gets overwritten with the new title/content. If it’s shorter or equal to 1, then it should just be the fallback page, so nothing changes (as there is no ‘else’ statement). The code itself is relatively straightforward - on line 15, I set up the generic page, and then I check if the length of the URL Path (everything after the domain) is longer than the length of “/” (so, 1). If the length is longer, that means there is a parameter given (in this case, the name), and the ‘hello’ variable gets overwritten with the new title/content. If it’s shorter or equal to 1, then it should just be the fallback page, so nothing changes (as there is no ‘else’ statement).
  
-After the ‘if’ statement, the rest of the viewHandler function is dictated by the templates package. The funcMap contains a map (for anyone who uses Python, they can be thought of as dictionaries) of filter names and the functions they map to. This could be used for custom functions as well. Afterwards, the template files are loaded. The function ‘template.Must’ simply ensures that the program throws an error and a panic if no template files are found. And lastly, the ExecuteTemplate function asks for a ResponseWriter (“w”), the name of the template to load (based off the filename), and the object to load (“hello”).+After the ‘if’ statement, the rest of the viewHandler function is dictated by the templates package. The funcMap contains a map (for anyone who uses Python, they can be thought of as dictionaries) of filter names and the functions they map to. This could be used for custom functions as well. Afterwards, the template files are loaded. The function ‘template.Must’ simply ensures that the program throws an error and a panic if no template files are found. And lastly, the ExecuteTemplate function asks for a ResponseWriter (“w”), the name of the template to load (based off the filename), and the object to load (“hello”).** 
 + 
 +Les URL 
 + 
 +Si vous lancez « go run » dans le répertoire du projet, une navigation à http://localhost:8081/ restituera un fichier « hello world » d'aspect habituel. Si, cependant, vous regardez à http://localhost:8081/Lucas, au lieu de ça, la page vous accueillera avec le nom donné dans l'URL. 
 + 
 +L'exemple est très basique - si vous voulez un peu de travail personnel, essayez (par exemple) de mettre correctement le nom en majuscules, même s'il est en minuscules dans l'URL. 
 + 
 +Le code lui-même est relativement simple - à la ligne 15, je paramètre la page générique et, ensuite, je vérifie que la longueur du chemin du L'URL (tout ce qui est après le domaine) est plus grande que la longueur de « / » (soit 1). Si cette longueur est plus grande, cela signifie qu'un paramètre est transmis (dans ce cas, le nom) et la variable « hello » est écrasée par le nouveau titre/contenu. Si elle plus courte ou égale à 1, alors il s'agit juste de la page de secours, sans aucun changement (car il n'y a pas de déclaration « else »). 
 + 
 +Après la déclaration » if », le reste de la fonction viewHandler est dicté par le paquet de modèles. funcMap contient un « map » ( pour toute personne qui utilise Python, ça ressemble aux dictionnaires) de noms de filtres et les fonctions vers lesquelles ils dirigent. Ils peuvent être aussi utilisés dans des fonctions personnalisées. Après cela, les fichiers de modèles sont chargés. La fonction « template.Must » assure simplement que le programme lance une erreur et une panique si aucun fichier de modèle n'est trouvé. Enfin, la fonction ExecuteTemplate réclame un ResponseWriter (« w »), le nom du modèle à charger (sur la base de son nom de fichier) et l'objet à charger (« hello »). 
 + 
 +**Structs 
 + 
 +Lines 9-12 create a struct called “Page” which contains two string fields - Title and Content. This is essentially creating a special data type. Structs can be initialized via Page{Title, Content}. Naturally, the more variables you include, the longer the initialization is.**
  
 Structs Structs
  
-Lines 9-12 create a struct called “Page” which contains two string fields - Title and Content. This is essentially creating a special data type. Structs can be initialized via Page{Title, Content}. Naturallythe more variables you include, the longer the initialization is.+Les lignes 9-12 créent un struct nommé « Page » qui contient deux champs de chaînes de caractères : Title (titre) et Content (contenu)Principalement, ça crée un type de donnée spécialles « structs » peuvent être initialisées via Page{Title, Content}. Naturellementplus il y a de variables incluses, plus l'initialisation est longue. 
 + 
 +**Debugging 
 + 
 +If you run into issuesyou can import the “fmt” package, and use fmt.Printf to print formatted text to the terminal.** 
 + 
 +Débogage 
 + 
 +Si, en fonctionnement, vous tombez sur des problèmes, vous pouvez importer le paquet « fmt » et utiliser « fmt.Printf » pour imprimer du texte formaté dans un terminal.
  
-Debugging+**Conclusion
  
-If you run into issues, you can import the “fmt” packageand use fmt.Printf to print formatted text to the terminal.+This is a very basic example, but should still serve as a jumping in point for anyone interested in working with Go. If anyone runs into issues, or has suggestions how to complete any of the steps in a more Go Fashion”, feel free to let me know at lswest34+fcm@gmail.com. Similarly, if you have any requests for article topics I should cover, you can let me know via email.**
  
 Conclusion Conclusion
  
-This is a very basic examplebut should still serve as a jumping in point for anyone interested in working with Go. If anyone runs into issuesor has suggestions how to complete any of the steps in a more “Go Fashion”feel free to let me know at lswest34+fcm@gmail.com. Similarlyif you have any requests for article topics I should coveryou can let me know via email.+Ceci est un exemple très basiquemais il devrait servir de point d'entrée à quiconque voudrait travailler avec Go. Si quelqu'un tombe sur des problèmesou a des suggestions pour finaliser l'une des étapes dans une version plus « à la mode de Go »n'hésitez pas à me le faire savoir à lswest34+fcm@gmail.com.  De mêmesi vous avez une quelconque demande pour un sujet d'article que je pourrais traitervous pouvez me le dire par mail.
  
issue121/c_c.1496069554.txt.gz · Dernière modification : 2017/05/29 16:52 de auntiee