首页  

go rest api server 及 go mod 实战     所属分类 go 浏览量 832
godemo/v2/main.go 

只有 main.go 

go run main.go
main.go:8:2: cannot find package "github.com/gorilla/mux" in any of:
        /usr/local/go/src/github.com/gorilla/mux (from $GOROOT)
        /Users/dugang/go/src/github.com/gorilla/mux (from $GOPATH)

go env
GO111MODULE="auto"
GOPROXY="https://goproxy.cn"

GOPROXY 推荐设置成 goproxy.cn
export GOPROXY=https://goproxy.cn


go mod init main
go: creating new go.mod: module main
go: to add module requirements and sums:
        go mod tidy

此时 go.mod 内容
module main

go 1.19


自动添加依赖 go mod tidy go: finding module for package github.com/gorilla/mux go: found github.com/gorilla/mux in github.com/gorilla/mux v1.8.0 go.mod 内容 module main go 1.19 require github.com/gorilla/mux v1.8.0 自动生成 go.sum
go run main.go 启动后 浏览器测试 http://127.0.0.1:8080 http://127.0.0.1:8080/todos http://127.0.0.1:8080/todos/1
main.go package main import ( "fmt" "log" "net/http" "github.com/gorilla/mux" ) func main() { router := mux.NewRouter().StrictSlash(true) router.HandleFunc("/", Index) router.HandleFunc("/todos", TodoIndex) router.HandleFunc("/todos/{todoId}", TodoShow) log.Fatal(http.ListenAndServe(":8080", router)) } func Index(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Welcome!\n") } func TodoIndex(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Todo Index!\n") } func TodoShow(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) todoId := vars["todoId"] fmt.Fprintf(w, "Todo show: %s\n", todoId) }
完整代码 https://gitee.com/dyyx/hellocode/tree/master/demo/go/rest-json-api/v3

上一篇     下一篇
docker 利用环境变量 设置 jvm 启动参数 系统参数

Go依赖管理 和 Go module使用

MAC M1 芯片

GO操作Mysql

余杭护国山

职场暗语