Golang使用redis连接池


package main

import (
	"github.com/gin-gonic/gin"
	"github.com/gomodule/redigo/redis"
	"log"
)

var redisPool *redis.Pool
var err error

func main() {

	redisPool = RedisPollInit()

	gin.SetMode(gin.ReleaseMode)

	r := gin.Default()

	r.GET("/", IndexAction)

	r.GET("/ping", PingAction)

	r.GET("/user/:name", UserAction)

	r.GET("/agent", AgentAction)

	r.GET("/admin", AdminAction)

	r.Run(":80")

}

func RedisPollInit() *redis.Pool {
	return &redis.Pool{
		MaxIdle:   3,
		MaxActive: 5,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", "127.0.0.1:6379")
			if err != nil {
				return nil, err
			}

			_, err = c.Do("AUTH", "123456")
			if err != nil {
				c.Close()
				return nil, err
			}
			return c, err
		},
	}
}

func IndexAction(c *gin.Context) {
	c.JSON(200, gin.H{"message": "index"})
}

func PingAction(c *gin.Context) {
	c.JSON(200, gin.H{"message": "pong"})
}

func UserAction(c *gin.Context) {
	c.String(200, "Hello %s", c.Param("name"))
}

func AgentAction(c *gin.Context) {
	c.String(200, c.GetHeader("user-agent"))
}

func AdminAction(c *gin.Context) {

	conn := redisPool.Get()
	defer conn.Close()

	data, err := redis.String(conn.Do("GET", "username"))
	if err != nil {
		log.Println(err)
		return
	}
	c.String(200, data)
}

发布于
归类为Golang

Golang实现API


package main

import (
	"database/sql"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"log"
)

var db *sql.DB
var err error

func main() {

	DatabaseInit()

	gin.SetMode(gin.ReleaseMode)

	r := gin.Default()

	r.GET("/", IndexAction)

	r.GET("/ping", PingAction)

	r.GET("/user/:name", UserAction)

	r.GET("/agent", AgentAction)

	r.Run()
}

func DatabaseInit() {

	db, err = sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/wordpress")
	if err != nil {
		log.Fatalln(err)
	}
	defer db.Close()

	db.SetMaxIdleConns(20)
	db.SetMaxOpenConns(20)

	err = db.Ping()
	if err != nil {
		log.Fatalln(err)
	}

}

func IndexAction(c *gin.Context) {
	c.JSON(200, gin.H{"message": "index"})
}

func PingAction(c *gin.Context) {
	c.JSON(200, gin.H{"message": "pong"})
}

func UserAction(c *gin.Context) {
	c.String(200, "Hello %s", c.Param("name"))
}

func AgentAction(c *gin.Context) {
	c.String(200, c.GetHeader("user-agent"))
}

发布于
归类为Golang

Golang使用数据库


package main

import (
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	"log"
	"net/http"
)

func IndexHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/" {
		w.Write([]byte("Index Page"))
	} else {
		w.Write([]byte("404"))
	}
}

func UserHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {

		var ID int
		var username, email string

		err := db.QueryRow("select ID, user_login, user_email from wp_users WHERE ID = 1").Scan(&ID, &username, &email)
		if err != nil {
			log.Print(err)
			return
		}

		w.Write([]byte(username))
	} else {
		w.Write([]byte("User Post"))
	}
}

var db *sql.DB
var err error

func main() {

	db, err = sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/wordpress")
	if err != nil {
		log.Fatalln(err)
	}
	defer db.Close()

	db.SetMaxIdleConns(20)
	db.SetMaxOpenConns(20)

	if err = db.Ping(); err != nil {
		log.Fatalln(err)
	}

	http.HandleFunc("/", IndexHandler)
	http.HandleFunc("/user", UserHandler)
	http.ListenAndServe(":8080", nil)
}

发布于
归类为Golang

Golang之切片Slice

// 创建切片
var slice1 []int
slice2 := []string
slice3 := []byte{'g', 'o', 'o', 'g', 'l', 'e'}

// 添加元素
slice1 = append(slice1, 1)

发布于
归类为Golang

Golang之Buffer缓冲器

// 创建 Buffer
import ""
var DataBuffer bytes.Buffer
var DataBuffer1 =  bytes.NewBuffer([]byte{})
var DataBuffer2 =  bytes.NewBufferString("abc")

// 写入数据
DataBuffer.Write([]byte("Hello"))
DataBuffer1.WriteString("Hello")
DataBuffer2.WriteByte([]byte("Hello"))

// 读取数据
DataBuffer.String()

发布于
归类为Golang

Go读写文件


package main

import (
	"fmt"
	"io/ioutil"
)

func ReadFile(file string) string {
	data, err := ioutil.ReadFile(file)
	if err != nil {
		return ""
	}
	return string(data)
}

func WriteFile(file string, content string) int {
	buffer := []byte(content)
	err := ioutil.WriteFile(file, buffer, 0666)
	if err != nil {
		return 0
	}
	return len(content)
}

func main() {
	write := WriteFile("1.txt", "abc")
	data := ReadFile("1.txt")
	fmt.Println(write)
	fmt.Println(data)
}

发布于
归类为Golang

Go实现http服务器


package main

import (
	"bytes"
	"io"
	"net/http"
)

func DefaultHandler(w http.ResponseWriter, req *http.Request) {

	var HtmlBuffer bytes.Buffer

	HtmlBuffer.WriteString("HTTP Method : ")
	HtmlBuffer.WriteString(req.Method)

	HtmlBuffer.WriteString("\nHTTP Proto : ")
	HtmlBuffer.WriteString(req.Proto)

	HtmlBuffer.WriteString("\nhttp Host : ")
	HtmlBuffer.WriteString(req.Host)

	HtmlBuffer.WriteString("\nRequest RemoteAddr : ")
	HtmlBuffer.WriteString(req.RemoteAddr)

	HtmlBuffer.WriteString("\nRequestURI : ")
	HtmlBuffer.WriteString(req.RequestURI)

	io.WriteString(w, HtmlBuffer.String())
}

func HttpServer(port string) {
	http.HandleFunc("/", DefaultHandler)
	http.ListenAndServe(port, nil)
}

func main() {
	HttpServer(":8080")
}

最简版本:


package main

import (
	"net/http"
)

func DefaultHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello World!"))
}

func main() {
	http.HandleFunc("/", DefaultHandler)
	http.ListenAndServe(":8000", nil)
}

带信号控制的版本:

package main

import (
	"context"
	"net/http"
	"os"
	"os/signal"
	"time"
)

func defaultHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello World!"))
}

func main() {
	shutdownSign := make(chan os.Signal)
	signal.Notify(shutdownSign, os.Interrupt)

	mux := http.NewServeMux()
	mux.HandleFunc("/", defaultHandler)

	var server *http.Server

	server = &http.Server{
		Addr:         ":8000",
		WriteTimeout: time.Second * 5,
		Handler:      mux,
	}

	go func() {
		<-shutdownSign
		server.Shutdown(context.Background())
	}()

	server.ListenAndServe()
}
发布于
归类为Golang

Go抓取网页


package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func HttpGet(url string) string {
	request, err := http.Get(url)
	if err != nil {
		return ""
	}

	defer request.Body.Close()
	respone, err := ioutil.ReadAll(request.Body)
	if err != nil {
		return ""
	}

	return string(respone)
}

func main() {
	html := HttpGet("http://www.mogublog.net")
	fmt.Println(html)
}
发布于
归类为Golang

GO语言学习笔记

GO语言学习笔记

一、定义变量

var variableName type = value (全局变量)
variableName := value (局部变量)

大写字母开头的变量其它包可以读取的,小写字母开头的就是私有变量

二、定义常量

const constantName = value

三、数据类型

1. 布尔值的类型为bool,值是true或false,默认为false
2. int和uint(int8, int16, int32, int64)
3. 浮点数的类型有float32和float64两种(没有float类型),默认是float64
4. 字符串都是采用UTF-8字符集编码,双引号或反引号定义,字符串是不可变的
5. Go内置有一个error类型,专门用来处理错误信息

四、数组

var arr [n]type
slice := []byte {'a', 'b', 'c', 'd'}

五、字典

var numbers map[string]int

六、函数

func funcName(input1 type1, input2 type2) (output1 type1, output2 type2) {
//这里是处理逻辑代码
//返回多个值
return value1, value2
}

发布于
归类为Golang