需求,main.go调用httpServer.go下的Start方法。
结构目录:
main.go中import 需要引用的文件路径
package main
import (
"fmt"
// 这里的路径开头为项目go.mod中的module
"engine_stability_platform/src/app/httpServer"
)
func main() {
fmt.Println("main.....")
httpServer.Start()
}
go.mod
这里要注意,如果不是根目录或者显示的是*.go的,说明go.mod的时候地址不对,把当前go.mod删除,然后进入到项目根目录,按照上述代码为engine_stability_platform,在控制台的终端,进入到该目录下
go mod init 模块名称
即
go mod init engine_stability_platform
然后会生成新的go.mod文件,内容如下所示
module engine_stability_platform
go 1.17
httpServer.go
package httpServer
import (
. "fmt"
"html"
"net/http"
"time"
)
var count int = 1
// 测试demo
func Task(w http.ResponseWriter, r *http.Request) {
Printf(" ------ here is Task[%d] ------- \n", count)
//defer r.Body.Close()
// 模拟延时
time.Sleep(time.Second * 2)
Fprintf(w, "Response.No.%d: Your request is %q\n\n", count, html.EscapeString(r.URL.Path))
count++
answer := `{"status:":"OK"}`
w.Write([]byte(answer))
}
func Task1(w http.ResponseWriter, r *http.Request) {
Printf(" ------ here is Task1[%d] ------- \n", count)
//defer r.Body.Close()
// 模拟延时
time.Sleep(time.Second * 2)
Fprintf(w, "Response.No[%d]: Your request is %q\n\n", count, html.EscapeString(r.URL.Path))
count++
answer := `{"status:":"OK"}`
w.Write([]byte(answer))
}
var server *http.Server
func Start() {
Println("===== This is http server =====")
mux := http.NewServeMux()
mux.HandleFunc("/hello/world", Task)
mux.HandleFunc("/hello/world1", Task1)
// 启动静态服务
http.Handle("/static/css/", http.FileServer(http.Dir("dist")))
http.Handle("/static/js/", http.FileServer(http.Dir("dist")))
if server != nil {
// 避免重复start server 端口泄露
server.Close()
}
// 设置服务器
server := &http.Server{
Addr: "127.0.0.1:8090",
Handler: mux,
}
// 设置服务器监听端口
server.ListenAndServe()
}
运行结果:
问题:
# command-line-arguments
./main.go:5:2: imported and not used: "engine_stability_platform/src/app/httpServer" as app
./main.go:13:2: undefined: httpserver
DIDI-C02G51DQQ05G:engine_stability_platform didi$ go run *.go
# command-line-arguments
./main.go:5:2: imported and not used: "engine_stability_platform/src/app/httpServer" as app
./main.go:13:2: undefined: httpserver
DIDI-C02G51DQQ05G:engine_stability_platform didi$ go run main.go
# command-line-arguments
./main.go:5:2: imported and not used: "engine_stability_platform/src/app/httpServer" as app
./main.go:13:2: undefined: httpServer
DIDI-C02G51DQQ05G:engine_stability_platform didi$ go run main.go
main.go:5:2: package engine_stability_platform/src/app/httpServer/httpServer is not in GOROOT (/usr/local/go/src/engine_stability_platform/src/app/httpServer/httpServer)
如果是在运行中出现以下类似问题,说明go.mod的时候地址不对,把当前go.mod删除,然后进入到项目根目录,按照上述代码为engine_stability_platform,在控制台的终端,进入到该目录下
go mod init 模块名称
既
go mod init engine_stability_platform
此时会生成一个新的mod文件,然后该文件的module就是根目录了
更多go mod命令使用,参考:https://blog.youkuaiyun.com/weixin_39689347/article/details/111215800