如今,Web 应用程序已成为生活的一部分。谷歌的Go语言是一种用于制作基于 Web 的应用程序的有用语言。我将向您展示如何开始在mac上使用 Go 。
设置 Go 环境
安装Go编程语言的最简单方法是使用homebrew。如果您还没有安装Homebrew,教程Homebrew Demystified: OS X's Ultimate Package Manager将向您展示如何安装。
在终端中,键入:
brew install go
找到 go 安装
要查找go install 目录的位置,请在终端程序中键入以下命令:
ls -la `which go`
你应该得到这个结果:
lrwxr-xr-x 1 raguay wheel 25 May 14 15:11 /usr/local/bin/go -> ../Cell/go/1.2.2/bin/go
这说明Go的主要安装是/usr/local/Cellar/go/1.2.2. 您需要将环境变量GOROOT设置为该目录的libexec目录。
在主目录中,创建目录go。go语言会将所有下载的包存储在那里。将此行添加到您的.bashrc文件和/或.zshrc文件中:
export GOPATH="/Users/<your user name>/go" export GOROOT="/<your go installation>/libexec"
如果您使用的是fish,请将其添加到您的config.fish文件中:
set -xg GOPATH "/Users/<your user name>/go" set -xg GOROOT "/<your go installation>/libexec"
要进行测试,请在终端中键入以下内容:
go version
它应该打印出 已安装的go版本。现在在我的系统上,它显示go version go1.2.2 darwin/amd64.
要检查更新的版本,让HomeBrew找出答案。在命令行上,键入:
brew update brew upgrade
update命令将获取更新程序的列表。upgrade命令执行实际升级。这样,您就不必寻找不同的网站来查找更新。
设置编辑器
现在Go在系统上,您需要设置编辑器。我经常使用Sublime Text 3、Vim和E Mac。因此,我需要让我的编辑跟上Go的速度。
对于Sublime Text来说,这很容易。为 Sublime Text安装包管理器。这允许简单的软件包安装。您要安装的软件包是goSublime。goSublime为您提供Go语言语法突出显示和Go构建系统。
要为Emacs安装Go语法高亮,请将$GOROOT/misc/emacs中的 eLisp 例程安装到您的 emacs elisp 文件夹中。要让Emacs加载新文件,请将此行添加到主文件夹中的 .emacs文件中:
(require 'go-mode-load)
对Vim的支持需要更多的工作。在终端中,运行以下bash命令行:
mkdir -p $HOME/.vim/ftdetect mkdir -p $HOME/.vim/syntax mkdir -p $HOME/.vim/autoload/go ln -s $GOROOT/misc/vim/ftdetect/gofiletype.vim $HOME/.vim/ftdetect/ ln -s $GOROOT/misc/vim/syntax/go.vim $HOME/.vim/syntax ln -s $GOROOT/misc/vim/autoload/go/complete.vim $HOME/.vim/autoload/go echo "syntax on" >> $HOME/.vimrc
仅当您的.vimrc中没有语法时才需要最后一行。
库以及如何使用它们
传统上,库是模块化代码以供重用的基础。在go中,库是包。Go 语言内置了许多包。您可以在包裹页面上浏览它们。还有许多3rd 方包和项目。
对于Title Case Server,我将使用第三方包web.go。它是一个简单的 Web 服务器框架,可简化在Go中创建基于 Web 的应用程序。要在您的系统上加载该软件包,请键入以下内容:
go install github.com/hoisie/web
install命令接受一个参数,该参数是一个不带http ://的网址,用于下载包。它被放置在之前创建的 $GOPATH 目录中。
项目:标题案例服务器
标题案例是最挑剔的事情之一。有些人喜欢某些单词总是小写。其他人认为单词应该都是标题大小写。因此,要正确地做到这一点(大多数包例程不这样做),您必须对照两个单词词典检查每个单词以确保一切正确。它使用一种新的编程语言是一个很棒的初学者项目。
// // Package: Main // // Description: This is the main package for the goTitleServer. // This is a simple web technology based title case // text server. // package main
//符号表示注释。编译器会忽略该行之后的所有内容。我喜欢评论一切。当你多年后阅读代码时,这些注释可以帮助你记住程序是如何工作的。
注释后的行是包声明。Go使用的每个文件都必须是包的一部分。每个程序只有一个必须具有main()函数的主包。这告诉编译器从哪里开始运行程序。
// // Import the libraries that we need for the server. // import ( "github.com/hoisie/web" "os" "strings" )
要使用包,您必须导入它们。所有使用的包都必须在此语句中。我包括两个用于操作系统功能的基本包os和用于操作字符串的字符串。github.com/hoisie/web加载web.go包来制作 web 服务器。
// // Function: homePage // // Description: This function will server the home page for inputing the string // to convert. // func homePage() string { return ` <!doctype html> <html> <head> <meta charset="utf-8" /> <title>Title Case Server</title> <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"> </script> <![endif]--> <style> body { width: 100%; } header { background: lightblue; width: 80%; height: 100px; margin: 20px auto; border-radius: 10px; } header h3 { text-align: center; padding-top: 40px; font-size: 28px; } content { font-size: 16px; } content form { font-size: inherit; margin: auto; padding-left: 8px; width: 80%; text-align: center; } content form p input { width: 80%; } content form button { margin: auto; border-radius: 10px; } </style> <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"> </script> <script type="text/JavaScript" > window.convert = function() { $.ajax({ type: "GET", url: "http://127.0.0.1:9910/titlecase/", data: { text: $("#text").val()} }).done(function(msg) { $("#result").val(msg); }); }; </script> </head> <body> <header> <h3>Title Case Server</h3> </header> <content> <form action="/titlecase/" method="get"> <p>Text to fix: <input id="text" type="text" name="text" > </input> </p> <button type="button" id="convert" text="Convert" onclick="window.convert();">Convert</button> <p>Results: <input id="result" type="text" name="result"> </input> </p> </form> </content> <footer> </footer> </body> </html> ` }
此函数创建主页。这是服务器提供给请求网站首页的网络浏览器的内容。func命令是一个函数声明。homePage是函数的名称。( )告诉编译器这个函数不接受任何输入。括号后面的字符串告诉编译器该函数将返回一个字符串。
{}内的所有内容都是函数的代码。这个函数很简单:将带引号的字符串返回给函数的调用者。在go中,您可以使用""、''和``引用字符串。我在这里使用了最后一个来获得一个根本没有处理的多行字符串。您称其为文字字符串。
通过使用文字引用方法,我可以像平常一样布局网页。刻度线内的任何内容都不会被编译器处理。它被直接复制到程序中,程序根据请求将其返回给网络浏览器。
// // Function: titleCase // // Description: This takes a string and converts it to Title case. It then // returns the string. // // Input: // val rest of the url if given any. // func titleCase(ctx *web.Context, val string) string { // // Get the string to convert and split it up by spaces. // words := strings.Split(ctx.Params["text"], " ") // // The array of words that should be lower case always, unless it is the first word // of the title. // lower := [...]string{"to", "an", "and", "at", "as", "but", "by", "for", "if", "in", "on", "or", "is", "with", "a", "the", "of", "vs", "vs.", "via", "via", "en"} // // The array of words that should be all upper case always. // upper := [...]string{"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "HTML", "css", "AT&T", "php"} // // For every word in the Title. // for i, _ := range words { // // Assume the word is not in the upper case or lower case arrays. // up := false low := false // // Loop through every word in the lower case array. // for j, _ := range lower { if strings.ToLower(words[i]) == lower[j] { // // It matches. Make sure the word in the array is the same. // Set the up flag as true. // words[i] = lower[j] low = true } } // // Loop through every word in the upper case array. // for k, _ := range upper { if strings.ToUpper(words[i]) == upper[k] { // // It matches. Make sure the word is the array is the same. // Set the low flag to true. // words[i] = upper[k] up = true } } // // If the word was not in the upper or lower array, then do a normal // title case conversion. This makes the first letter upper case and all // the other letters lower case. // if (!up) && (!low) { words[i] = strings.Title(words[i]) } } // // Make sure the first word is title case! // words[0] = strings.Title(words[0]) // // Return the Title by joining all the words with a space. // return strings.Join(words, " ") }
这段代码完成了将提供给 Web 服务器的字符串转换为标题大小写等效项的工作。
ctx *web.Context, val 字符串告诉编译器该函数接收两个变量。一种是指向 web.go 包中定义的web.Context数据结构的指针。另一个是字符串。您通过名称和变量类型声明变量输入。
*符号表示指针。指针是指向数据结构在内存中的位置的地址。Go遵循C数据指针格式。
第一条语句获取浏览器传递给服务器的名为text的参数,并用空格将其拆分。strings.Split调用strings包内的Split函数。您可以想到类似于 C++ 中的 Objects 的包。您使用. 包名和函数名之间。
在每个包中,每个以 ac api tal 字母开头的函数都可以从包外部访问。每个以小写字母开头的函数只能从包内部访问。
当strings.Split函数通过分隔符拆分字符串时,它返回一个字符串数组。然后将输出分配给变量words。要创建一个新变量,第一次使用它时,您必须使用:=来分配它。如果要将相同的变量更改为另一个字符串数组,则可以使用=运算符。
接下来,为不同的单词列表创建两个数组。lower表示所有小写单词,upper表示所有大写单词。[ ...]告诉编译器从数据中获取分配的数量。这样您就可以将单词添加到列表中,而不必担心增加计数。该字符串告诉编译器数组中的每个条目都是一个字符串。
我正在使用for..range循环对数组进行排序。第一个循环遍历输入中给出的每个单词,而另外两个循环遍历每个单词的每个单词字典。它首先将单词转换为小写,然后将其与下层词典中的每个单词进行比较。如果有匹配项,它会通过将单词位置分配给字典中的字符串来强制单词全部小写。然后它使用上层字典执行完全相同的操作。
如果该词不在任一字典中,则对该词执行strings.Title函数。这会强制第一个字母为大写字母,其余字母为小写字母。
最后,无论如何,第一个单词都成为标题大小写。strings.Join函数使用空格组装字符串数组。它将结果返回给函数的调用者。
// // Function: killServer // // Description: This function will stop the server. // func killServer() string { os.Exit(0) return "" }
killServer函数正如其名称所暗示的那样:杀死 Web 服务器。它包装了对os包中os.Exit()函数的调用。
// // Function: main // // Description: This is the main function that is called upon program running. // func main() { // // set the titlecase web address to the proper function. // web.Get("/titlecase/(.*)", titleCase) // // Set up a path to kill the server. // web.Get("/kill", killServer) // // send the home page to the proper function. // web.Get("/", homePage) // // Run the server on the local machine at port 9911 // web.Run("127.0.0.1:9910") }
主函数使用web.Get为主页、杀戮页面和标题大小写转换器例程设置Get协议路由。web是我们之前下载的web.go包。Get定义了一个HTML Get请求。您还可以定义Put、post和Delete运算符。
web.Run语句在给定的地址和端口上启动 Web 服务器。web.go包从那里接管并在定义的地址被请求时调用您的例程。
编译
现在程序已经完成,您需要编译它。要编译一个Go程序,你告诉它用 main 函数构建文件。要编译此程序,请键入:
go build goTitleServer.go
完成后,您将在目录中拥有goTitleServer。这就是完整的程序。您可以使用以下命令启动它:
./goTitleServer
然后打开网络浏览器访问http://127.0.0.1:9910。你应该看到这个:
goTitleServer 正在运行
在Text to fix:文本框中输入您的字符串,按Convert,转换后的字符串将出现在Results:文本框中。
标题案例服务器工作流程
我很自然地将这个程序放入了alfred工作流程中。它是与goTitleServer.go文件一起下载的一部分。这给出了在没有 Web 浏览器的情况下使用服务器的示例。它使用以下 bash 代码来查询服务器:
query=`echo "{query}" | sed -e 's/ /+/g'`;curl "http://localhost:9910/titlecase/?text=$query";
第一行将查询字符串中的所有空格更改为+。curl命令是用于从 Web 服务器获取信息的标准 unix 命令。命令行将使用curl命令发送一个 url 请求,如网页将创建的发送给它。将字符串转换为标题大小写的结果中返回的内容。
此工作流的Alfred 提示命令是:
tis:launch – 此命令启动服务器。您必须先启动服务器,然后才能进行转换。
tcs: convert——这个命令需要一个字符串来转换。工作流在通知中显示结果并将其复制到剪贴板。
tcs:kill –此命令会终止 Web 服务器。
您还需要分配一个热键来获取当前选择并通过标题案例服务器运行它并将其粘贴回原位。
结论
现在您已经将系统配置为使用Go编写和编译 Web 应用程序,您需要开始编写一些!使用这个代码库并将其扩展为更多的文本处理功能,以制作一个出色的文本处理服务器。