Tag Archives: go语言

Hello World

go语言入门[3]—-并发&线程通讯

go语言的的多线程是通过“goroutine”来实现的,通过“go”关键字新建一个goroutine
比如:

    go hello()

其实,goroutine比线程更小,“十几个goroutine可能体现在底层也就五六个线程”,且是内存共享的

不同的goroutine之间,通过channel来通讯,比如下面的的程序,主线程是一个http sever,收到http请求后,将url塞入channel,然后下面的“see”函数在来处理这个channel

package main
 
import (
	"fmt"
    "net/http"
)
//定义一个channel
var cc chan string
 
func main() {
    fmt.Println("--ubox-event--start--")
 
    //新建一个channel	
    cc = make(chan string)
    //使用一个goroutine启动see函数,编号为1
    go see("1")
    //启动httpServe
    http.HandleFunc("/*", httpServe)
    http.ListenAndServe(":8008", nil)
}
 
func httpServe(w http.ResponseWriter, req *http.Request) {
    url := req.URL.String()
    w.Write([]byte("Hello"))
    //将url塞入channel
    cc <- url
}
 
func see(n string) {
    fmt.Println("--see--" + n + "--start--")
    //通过range参数取出channel,每当上面httpServe被塞入一次,这里即执行一次
    for s := range cc {
        fmt.Println("--see--url-" + n + "-" + s)
    }
}

go run 启动上面的程序,然后访问localhost:8008/xxxxx,便会看到 “–see–url-1-/xxxxx”

有意思的是 ,如果你在上面再启动两个goroutine,即go see(“2″),go see(“3″)

然后不断访问localhost:8008/xxxxx,打印出来的并不一直是 “url-1”,而是 url-1、url-2、url-3轮流出现,且每次访问只出现一次,也就是说channel并不会一直分配给第一个range

Hello World

go语言入门[1]—-发邮件

这里说的发邮件,用的是“net/smtp”,不多说,看代码

package main
 
import (
	"net/smtp"
	"fmt"
	"strings"
)
 
//对发送接口的简单封装
func SendMail(to, subject, body, mailType string) error{
	//发件服务器相关配置,这里以gmail为例
	u := "xxxxx@gmail.com"
	p := "xxxx"
	host := "smtp.gmail.com"
	port := "25" 
	//Auth
	auth := smtp.PlainAuth("", u, p, host)
	var content_type string
	if mailType == "html" {
		content_type = "Content-Type: text/html; charset=UTF-8"
	}else{
		content_type = "Content-Type: text/plain; charset=UTF-8"
	}
	msg := []byte("To:" + to + "\r\nForm: 老大<" + u + ">\r\nSubject: " 
		+ subject + "\r\n" + content_type + "\r\n\r\n" + body)
	send_to := strings.Split(to, ";")
	//发信
	err := smtp.SendMail((host + ":" + port), auth, u, send_to, msg)
	return err
}
 
func main() {
	to := "xxxx@163.com;xxxx@gmail.com"
	subject := "test-go-smtpxxx"
	body := "<html><body><hr><h1>test-smtpxxx</h1><hr></body></html>"
 
	fmt.Println("send email")
	err :=  SendMail(to, subject, body, "html")
	if err != nil {
		fmt.Println("mail error: %v", err)
	}else{
		fmt.Println("mail ok!")
	}
}