go 自动重载代码

阅读 26

2022-02-25

go的开始/自动重载代码

go 编码开始

如何创建go 的项目

如何使用go run命令运行go程序

创建main.go 文件

package main

import (
    "fmt"
    "net/http"
)

func handlerFunc(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "<h1>Hello, world</h1>")
}
func main() {
    http.HandleFunc("/", handlerFunc)
    http.ListenAndServe(":3000", nil)
}

Go应用中 package main 的规则

标准库 fmt 包的基本使用

fmt.Fprint(w, "<h1>Hello, 这里是 goblog</h1>")

标准库 http 包的基本使用

func handlerFunc(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "<h1>Hello, 这里是 goblog</h1>")
}

func main() {
    http.HandleFunc("/", handlerFunc)
    http.ListenAndServe(":3000", nil)
}

http.ListenAndServe

http.ListenAndServe(":3000", nil)

http.HandleFunc

fmt.Fprint(w, "<h1>Hello, 这里是 goblog</h1>")

http.Request

http.ResponseWriter

http 包中如何通过url 路径来处理业务逻辑

http.HandleFunc("/", handlerFunc)
package main

import (
    "fmt"
    "net/http"
)

func handlerFunc(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "<h1>Hello, 这里是 goblog</h1>")
    fmt.Fprint(w, "请求路径为:"+r.URL.Path)
}

func main() {
    http.HandleFunc("/", handlerFunc)
    http.ListenAndServe(":3000", nil)
}
fmt.Fprint(w, "请求路径为:"+r.URL.Path)
go run main.go
package main

import (
    "fmt"
    "net/http"
)

func handlerFunc(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path == "/" {
        fmt.Fprint(w, "<h1>Hello,  这里测试</h1>")
    } else if r.URL.Path == "/about" {
        fmt.Fprint(w, "关于我们")
    } else {
        fmt.Fprint(w, "<h1>请求页面未找到!</h1>")
    }
}

func main() {
    http.HandleFunc("/", handlerFunc)
    http.ListenAndServe(":3000", nil)
}

如何使用 air 来自动重载代码

安装air

GO111MODULE=on  go install github.com/cosmtrek/air@latest
air -v

  __    _   ___
 / /\  | | | |_)
/_/--\ |_| |_| \_ , built with Go

air

air

在这里插入图片描述

精彩评论(0)

0 0 举报