golang mail、shell、cookie、uuid

RunMonster發表於2020-10-13

mail

package main

import (
	"fmt"
	"net/smtp"
	"strings"
)

func sendMain(subject string, body string, to string)  {
	//這裡需要申請授權碼
	auth := smtp.PlainAuth("", "5914@qq.com", "waeeg", "smtp.qq.com")
	tos := []string{to}
	nickname := "管理員"
	user := "5914@qq.com"
	content_type := "Content-Type: text/plain; charset=UTF-8"
	msg := []byte("To: " + strings.Join(tos, ",") + "\r\nFrom: " + nickname +
		"<" + user + ">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
	err := smtp.SendMail("smtp.qq.com:25", auth, user, tos, msg)
	if err != nil {
		fmt.Printf("send mail error: %v", err)
	}
}

func main() {
	sendMain("標題", "內容","5914@qq.com")
}

shell

package main

import (
	"bytes"
	"fmt"
	"log"
	"os/exec"
	"strings"
	"sync"
)

/*
執行一個shell指令碼
*/
func exec_shell(s string) {
	cmd := exec.Command("/bin/bash", "-c", s)
	var out bytes.Buffer

	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s", out.String())
}

func exe_cmd(cmd string, wg *sync.WaitGroup) {
	fmt.Println(cmd)
	parts := strings.Fields(cmd)
	out, err := exec.Command(parts[0], parts[1]).Output()
	if err != nil {
		fmt.Println("error occured")
		fmt.Printf("%s", err)
	}
	fmt.Printf("%s", out)
	wg.Done()
}

func main() {
	exec_shell("uname ")

	wg := new(sync.WaitGroup)
	commands := []string{"echo newline >> foo.o", "echo newline >> f1.o", "echo newline >> f2.o"}
	for _, str := range commands {
		wg.Add(1)
		go exe_cmd(str, wg)
	}
	wg.Wait()
}

cookie

package main

import (
	"fmt"
	"net/http"
)

/*
cookie與session的區別
cookie儲存在客戶端的純文字檔案
使用者請求伺服器指令碼
指令碼設定cookie內容 並 通過http-response傳送cookie內容到客戶端並儲存在客戶端本地
客戶端再次傳送http請求的時候會將本地的cookie內容新增到http請求頭髮送給伺服器,伺服器端指令碼可以呼叫cookie內容

session是儲存在伺服器的檔案 cookie內容儲存在客戶端,存在被客戶篡改的情況,session儲存在客戶端防止被使用者篡改的情況。
*/
func main() {
	http.HandleFunc("/", set)
	http.HandleFunc("/read", read)
	http.ListenAndServe(":8080", nil)
}

func set(w http.ResponseWriter, req *http.Request) {
	http.SetCookie(w, &http.Cookie{
		Name:  "my-cookie",
		Value: "some value",
	})
	fmt.Fprintln(w, "COOKIE WRITTEN - CHECK YOUR BROWSER")
}

func read(w http.ResponseWriter, req *http.Request) {
	c, err := req.Cookie("my-cookie")
	if err != nil {
		http.Error(w, http.StatusText(400), http.StatusBadRequest)
		return
	}

	fmt.Fprintln(w, "YOUR COOKIE:", c)
}

uuid

package main

import (
	"fmt"
	"github.com/satori/go.uuid"
)

func main() {
	// 建立
	u1 := uuid.NewV4()
	fmt.Printf("UUIDv4: %s\n", u1)

	// 解析(字串轉uuid物件)
	u2, err := uuid.FromString("f5394eef-e576-4709-9e4b-a7c231bd34a4")
	if err != nil {
		fmt.Printf("Something gone wrong: %s", err)
		return
	}
	fmt.Printf("Successfully parsed: %s", u2)
}

 

相關文章