golang 交差编译与打包容器

build.sh

1#!/usr/bin/env bash
2CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o webdemo .
3docker build -t rushui/webdemo .

Dockerfile

1FROM alpine:latest
2COPY ./webdemo /usr/local/bin/webdemo
3WORKDIR /usr/local/bin/
4EXPOSE 8080
5CMD [ "webdemo" ]

webdome示例(go)

 1package main
 2
 3import (
 4	"database/sql"
 5	"fmt"
 6	_ "github.com/go-sql-driver/mysql"
 7	"net/http"
 8)
 9
10func IndexHandler(w http.ResponseWriter, r *http.Request) {
11	_, _ = fmt.Fprintln(w, "hello rushui")
12}
13
14func RowsHandler(w http.ResponseWriter, r *http.Request) {
15	//第⼀步:打开数据库,格式是 ⽤户名:密码@/数据库名称?编码⽅式
16	db, err := sql.Open("mysql", "root:root@tcp(mysql-dev:3306)/test?charset=utf8")
17	if err != nil {
18		fmt.Println(err)
19	}
20	//关闭数据库
21	var id int
22	var name string
23	//查询数据,指定字段名,返回sql.Rows结果集
24	rows, err := db.Query("select id,name from user")
25	if err != nil {
26		fmt.Println(err)
27	}
28	defer rows.Close()
29	for rows.Next() {
30		_ = rows.Scan(&id, &name)
31		_, _ = fmt.Fprintln(w, name)
32	}
33}
34
35func main() {
36	http.HandleFunc("/", IndexHandler)
37	http.HandleFunc("/rows", RowsHandler)
38	_ = http.ListenAndServe(":8080", nil)
39}

发布日期:2023-03-06 23:00 字数:156 用时 1分钟
tags:Golang 容器