Debian 10 开发一个go语言接口
首先是安装go环境
# 1、预备工作 sudo apt-get update sudo apt-get -y install wget gcc make # 2、下载go安装包 wget https://dl.google.com/go/go1.16.2.linux-amd64.tar.gz # 3、解压 sudo tar -C /usr/local -xzf go1.16.2.linux-amd64.tar.gz # 4、环境配置 nano /etc/profile # 添加到末尾 export PATH=$PATH:/usr/local/go/bin export GOPATH=$HOME/go # 5、使配置生效 source /etc/profile # 验证 / 打印 go 版本 go version
go环境配置结束,进入正题,很多coder喜欢golang的高并发,但是我们这种小项目真的是~ 有些多余,纯体验下
1、go安装sql库,我用的MariaDB,就是Mysql的分支,用mysql的库就行
go get -u github.com/go-sql-driver/mysql # 一般情况下,都是要设置代理的 github得翻一翻
2、直接代码展示了
package main import ( "database/sql" "encoding/json" "fmt" "net/http" "strconv" _ "github.com/go-sql-driver/mysql" ) func main() { http.HandleFunc("/search", ocrHandler) http.ListenAndServe(":8080", nil) } func ocrHandler(w http.ResponseWriter, r *http.Request) { // 参数处理 keyword := r.FormValue("keyword") page := 1 pageParam := r.FormValue("page") if pageParam != "" { pageInt, err := strconv.Atoi(pageParam) if err == nil { page = pageInt } } // 连接数据库 db, err := sql.Open("mysql", "root:123456@tcp(localhost:3306)/VIVA") if err != nil { fmt.Println(err) return } defer db.Close() // 总数量 var count int rowscount, err := db.Query("SELECT count(1) FROM ocr WHERE path LIKE ? or content LIKE ? ", "%"+keyword+"%", "%"+keyword+"%") if err != nil { fmt.Println(err) return } defer rowscount.Close() for rowscount.Next() { if err := rowscount.Scan(&count); err != nil { // 处理错误 fmt.Println(err) return } } if err := rowscount.Err(); err != nil { // 处理错误 fmt.Println(err) return } // 查询数据 offset := (page - 1) * 20 rows, err := db.Query("SELECT id,title,path FROM ocr WHERE path LIKE ? or content LIKE ? ORDER BY id DESC LIMIT ?, 20", "%"+keyword+"%", "%"+keyword+"%", offset) if err != nil { fmt.Println(err) return } defer rows.Close() // 解析结果 var ocrs []map[string]interface{} for rows.Next() { var id int var path string var title string err := rows.Scan(&id,&path,&title) if err != nil { fmt.Println(err) continue } ocr := map[string]interface{}{ "id":id, "path":path, } ocrs = append(ocrs, ocr) } // 输出结果 data := map[string]interface{}{ "code": 200, "msg": "success", "data":map[string]interface{}{ "total" : count, "lists" : ocrs, }, } json.NewEncoder(w).Encode(data) }
3、接着编译下,就可以执行了
go build main.go ./main
4、配置api接口自动启动
# /etc/systemd/system/main.service [Unit] Description=Search API for OCR After=network.target [Service] Type=simple WorkingDirectory=/usr/bin/goLang ExecStart=/usr/bin/goLang/main Restart=on-failure User=root [Install] WantedBy=multi-user.target
5、对应服务命令
# 启动服务 sudo systemctl start main.service # 停止服务 sudo systemctl stop main.service # 重启服务 sudo systemctl restart main.service # 查看服务状态 sudo systemctl status main.service # 开机启动服务 sudo systemctl enable main.service # 禁用开机启动服务 sudo systemctl disable main.service